How to test endianness in node.js

妖精的绣舞 提交于 2019-12-12 10:45:38

问题


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.



来源:https://stackoverflow.com/questions/10316803/how-to-test-endianness-in-node-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!