How to test endianness in node.js

2019-06-22 12:54发布

问题:

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?

回答1:

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



回答2:

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



回答3:

You should not need to test the endianness of the host system.

You need to investigate which byte-order the buffer is formatted using, and use the correct variant to read it out again.