Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test endianness in node.js

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?

like image 948
Gabriel Llamas Avatar asked Apr 25 '12 13:04

Gabriel Llamas


People also ask

How do I test my endian machine?

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.

How do I get endianness in node js?

os.endianness() Returns the endianness of the CPU. Possible values are "BE" or "LE".

How do you check if a number is big-endian or little endian?

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.

How do you read little endian?

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.


2 Answers

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

like image 57
zamnuts Avatar answered Sep 21 '22 06:09

zamnuts


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

like image 40
Mikola Avatar answered Sep 20 '22 06:09

Mikola