Js将数字转换为缓冲区数组[4](Js Convert number into buffer array[4])

我想将一个数字值打印成一个4值的数组[uint32_t]

例子255 => [0x00, 0x00, 0x00, 0xFF]

想要将此值从Nodejs服务器发送到Arduino

是否存在任何原生溶剂或命题?

I want to print a number value into an array of 4 value [ uint32_t]

Exemple 255 => [0x00, 0x00, 0x00, 0xFF]

a want to send this value from Nodejs server to Arduino

is there any native sollution or proposition ?

最满意答案

有很多方法可以做到这一点 - 例如,您可以移动数字并将所有位移零,但是除了8个最不重要的位。

例如:

const conv = num => [ (num >> 24) & 255, (num >> 16) & 255, (num >> 8) & 255, num & 255, ]; console.log(conv(16)); console.log(conv(255)); console.log(conv(256)); console.log(conv(640)); console.log(conv(32768));

或者,你可以采用一种完全不同的方法,而不是告诉计算机如何精确地移位这些位,你可以告诉它获得一个4字节的缓冲区,存储一个32位的数字并以四个数组的形式显示给你。位数,在JavaScript中使用新的类型数组:

const conv = num => { let b = new ArrayBuffer(4); new DataView(b).setUint32(0, num); return Array.from(new Uint8Array(b)); } console.log(conv(16)); console.log(conv(255)); console.log(conv(256)); console.log(conv(640)); console.log(conv(32768));

结果是一样的,但这次你不需要知道移位的方法以及如何掩盖它们。 这是使用JavaScript的一些新功能。 有关详情,请参阅:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Typed_arrays https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView

请注意,这都是使用big-endian格式,如您问题中的示例。 但请记住,数字也可以用小端格式表示。 看到:

https://en.wikipedia.org/wiki/Endianness

There are many ways to do it - e.g. you can shift the numbers and zero out all the bits but the 8 least significant ones.

For example:

const conv = num => [ (num >> 24) & 255, (num >> 16) & 255, (num >> 8) & 255, num & 255, ]; console.log(conv(16)); console.log(conv(255)); console.log(conv(256)); console.log(conv(640)); console.log(conv(32768));

Or, you can take a completely different approach and instead of telling the computer how to exactly shift the bits, you can tell it to get a 4 byte buffer, store a 32-bit number and show it to you as an array of four 8-bit numbers, using the new typed arrays in JavaScript:

const conv = num => { let b = new ArrayBuffer(4); new DataView(b).setUint32(0, num); return Array.from(new Uint8Array(b)); } console.log(conv(16)); console.log(conv(255)); console.log(conv(256)); console.log(conv(640)); console.log(conv(32768));

The result is the same but this time you don't need to know which way to shift bits and how to mask them. This is using some new features of JavaScript. For more info see:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Typed_arrays https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView

Note that this is all using big-endian format like the example in your question. But keep in mind that numbers can be represented with little-endian formats as well. See:

https://en.wikipedia.org/wiki/Endianness

更多推荐