问题描述
对于从微控制器转换数据我有些困惑。我想发送和接收Ints,因此我将1100转换为十六进制,即44c,但我需要将其分为2个字节44和0c,因为控制器首先希望低字节:
十进制:1100十六进制:044c
控制器等待:字节[0x0c],字节[0x44](按此顺序)
这真的让我头疼,因为我不想将其转换为字符串和拆分等。当我从mc收到消息时,我遇到了同样的挑战,因为我首先收到了低字节。
我不习惯JavaScript中的这类内容,需要帮助。
解决方法
您可以使用Buffer
s,它是node.js中的字节数组,可让您使用一些简单的I / O BE和LE函数,如下所示:
const buf = Buffer.alloc(2); //similar to malloc
const number = 1100;
buf.writeUInt16BE(number);
console.log(buf); //04 4c
buf.writeUInt16LE(number);
console.log(buf); //4c 04
如果相反,您一次需要访问正好4位,则需要bitwise运算符(例如>>
和&
):
const GetNthNibble = (number,nth) => (number >> 4*nth) & 0xF;
const number = 0x1234;
console.log(GetNthNibbles(number,0)); //4
console.log(GetNthNibbles(number,1)); //3
console.log(GetNthNibbles(number,2)); //2
console.log(GetNthNibbles(number,3)); //1