将字节数组(char数组)转换为整数类型(short,int,long) [英] Converting byte array (char array) to an integer type (short, int, long)

查看:1487
本文介绍了将字节数组(char数组)转换为整数类型(short,int,long)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道当将字节数组转换为short / int / long时,系统字节顺序是否重要。如果代码在big-endian和little-endian机器上运行,这是不正确的吗?

I was wondering if system endianness matters when converting a byte array to a short / int / long. Would this be incorrect to do if the code runs on both big-endian and little-endian machines?

short s = (b[0] << 8) | (b[1]);
int i = (b[0] << 24) | (b[1] << 16) | (b[2] << 8) | (b[3])


推荐答案

在小端字节中,你在short或int的上部有最高有效字节,即短8-15位,int为24-31。对于big endian,字节顺序需要颠倒:

Yes, endianness matters. In little endian you have the most significant byte in the upper part of the short or int - i.e. bits 8-15 for short and 24-31 for int. For big endian the byte order would need to be reversed:

short s = ((b[1] << 8) | b[0]);
int i = (b[3] << 24) | (b[2] << 16) | (b[1] << 8) | (b[0]);

请注意,这假设字节数组是小字节顺序。字节数组和整数类型之间的字节序和转换不仅取决于CPU的字节顺序,还取决于字节数组数据的字节顺序。

Note that this assumes that the byte array is in little endian order. Endianness and conversion between byte array and integer types depends not only on the endianness of the CPU but also on the endianness of the byte array data.

建议将这些(通过编译标志或在运行时)知道系统的字节顺序并正确执行转换的函数中的转换。

It is recommended to wrap these conversions in functions that will know (either via compilation flags or at run time) the endianness of the system and perform the conversion correctly.

此外,为字节数组数据创建一个标准(例如总是大端),然后使用 socket ntoh_s ntoh_l 会将有关字节序的决定卸载到OS socket 实现知道这样的事情。请注意,默认网络顺序是大尾数法( n ntoh_x 中),因此字节数组数据为大

In addition, creating a standard for the byte array data (always big endian, for example) and then using the socket ntoh_s and ntoh_l will offload the decision regarding endianness to the OS socket implementation that is aware of such things. Note that the default network order is big endian (the n in ntoh_x), so having the byte array data as big endian would be the most straight forward way to do this.

如OP(@Mike), boost 也提供了字节序转换函数。

As pointed out by the OP (@Mike), boost also provides endianness conversion functions.

这篇关于将字节数组(char数组)转换为整数类型(short,int,long)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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