10

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?

Community
  • 1
  • 1
Gabriel Llamas
  • 18,244
  • 26
  • 87
  • 112
  • On what basis are you making the assumption that the file you're reading from was written by the same computer? Shouldn't you worry about knowing the endianness of the computer that wrote the file? If you have to read from a file, need to worry about endianness and the file doesn't contain metadata, then the file format is bad. – Romain Apr 25 '12 at 13:39
  • @Romain - what if you are listening for IPC messages on a unix-dgram or unix domain socket? I might reasonably expect the endianness to be the same then (unless an endianness for the writer was explicitly documented). – jimbobmcgee Jun 18 '12 at 13:55
  • @jimbobmcgee If it's a socket and the protocol is strict (e.g. specifies endianness), then you know the endianness, and are in the same situation as if you had a file format that has a BOM of some kind. If not, relying on the source emitting stuff in a specific way is a bad decision, unless you also own the code of the source (then again, why worry about checking?) – Romain Jun 19 '12 at 09:04

2 Answers2

14

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

zamnuts
  • 9,492
  • 3
  • 39
  • 46
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

Mikola
  • 9,176
  • 2
  • 34
  • 41