如何在node.js中测试字节序 [英] How to test endianness in node.js

查看:76
本文介绍了如何在node.js中测试字节序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当读取大量字节并将其转换为数字时,node.js具有类似 buffer.readInt32BE() buffer.readInt32LE()。



如果我只知道文件的前4个字节是整数,则应使用什么函数如果我不知道系统的字节序?大字节序还是小字节序?



进行快速谷歌搜索( stackoverflow ),在C语言中我们可以测试字节序:

  if(htonl( 47)== 47){
//大端
} else {
//小端。
}

我们如何测试node.js中的字节序以正确使用readInt32BE和readInt32Le ?

解决方案

os.endianness()返回CPU的字节序。可能的值为 BE或 LE。



它是在Node.js v0.10.0中添加的,它不包含在< = v0.8.25中。 / p>

来源: http://nodejs.org /api/os.html#os_os_endianness


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?

解决方案

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

这篇关于如何在node.js中测试字节序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆