When you read a chunk of bytes and you need to convert them to a number, node.js has functions like buffer.readInt32BE()
and buffer.readInt32LE()
.
If I only know that the first 4 bytes of a file is an integer, what function should I use if I don't know the endianness of the system? Big endian or little endian?
Doing a fast googling (stackoverflow), in C we can test the endianness doing:
if ( htonl(47) == 47 ) {
// Big endian
} else {
// Little endian.
}
How can we test the endianness in node.js to properly use readInt32BE and readInt32Le?
We can write a small tool to test Whether a Machine is Big Endian or Little Endian in C/C++. First, we declare a 16-bit integer (short int), which has the value 0x0001, then we gets its pointer and deference it. If the MSB is stored at lower address (e.g. the value that pointer points to), then it is little endian.
os.endianness() Returns the endianness of the CPU. Possible values are "BE" or "LE".
In little endian machines, last byte of binary representation of the multibyte data-type is stored first. On the other hand, in big endian machines, first byte of binary representation of the multibyte data-type is stored first.
In the case of little endian format, the least significant byte appears first, followed by the most significant byte. The letter 'T' has a value of 0x54 and is represented in 16 bit little endian as 54 00.
os.endianness()
returns the endianness of the CPU. Possible values are "BE" or "LE".
It was added in Node.js v0.10.0, it is not included in <= v0.8.25.
Source: http://nodejs.org/api/os.html#os_os_endianness
Totally possible, and even reasonable to do if you are working with typed arrays. I wrote a quick module to check if your system is little endian on node.js:
https://npmjs.org/package/is-little-endian
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With