[英]How can I convert the following Java code to Node.js?
I have the following Java code: 我有以下Java代码:
int data = Float.floatToIntBits(4.2);
sendCommand(0x50, data);
public void sendCommand(byte type, int data) {
byte[] cmd = new byte[FRAME_LENGTH];
cmd[0] = type;
cmd[1] = (byte)(data);
cmd[2] = (byte)(data >>> 8);
cmd[3] = (byte)(data >>> 16);
cmd[4] = (byte)(data >>> 24);
printFrame(cmd);
}
I need to convert it to Node.js. 我需要将它转换为Node.js. I first thought to use the Buffer module, but I have no idea how to interpret the above code.
我首先想到使用Buffer模块,但我不知道如何解释上面的代码。 Here is my attempt, but it doesn't seem correct:
这是我的尝试,但似乎不正确:
const type = 0x50;
const data = 25;
function sendCommand(type, data) {
const buff = Buffer.from([type, data, data >>> 8, data >>> 16, data >>> 24]);
console.debug(buff);
}
Can you advise? 你能建议吗?
I was pretty close... 我非常接近......
Since JavaScript converts hex data to integer on the fly, we need to set them as a string. 由于JavaScript动态地将十六进制数据转换为整数,因此我们需要将它们设置为字符串。 So, instead of:
所以,而不是:
const type = 0x50;
We have to use: 我们必须使用:
const type = '0x50';
So, the equivalent of the Node.js program to the Java program posted in the question would be: 因此,相对于问题中发布的Java程序的Node.js程序将是:
const type = '0x50';
const data = 25;
sendCommand(type, data);
function sendCommand(type, data) {
const buff = Buffer.from([type, data, data >>> 8, data >>> 16, data >>> 24]);
console.debug(buff);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.