如何将以下Java代码转换为Node.js?

时间:2019-05-21 15:22:11

标签: java node.js binary

我有以下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);
}

我需要将其转换为Node.js。我首先想到要使用Buffer模块,但是我不知道如何解释以上代码。这是我的尝试,但似乎不正确:

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);
}

你能建议吗?

1 个答案:

答案 0 :(得分:0)

我离我很近...
由于JavaScript会即时将十六进制数据转换为整数,因此我们需要将其设置为字符串。因此,代替:

const type = 0x50;

我们必须使用:

const type = '0x50';

因此,与问题中发布的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);
}