在C/C++中,您可以使用union:
union Foo {
unsigned char bytes[sizeof(short)];
short value;
};
. . .
bool isBigEndian()
{
Foo foo;
foo.value = 0x0102;
return foo.bytes[0] == 0x01;
}
. . .
Foo foo;
if (isBigEndian()) {
foo.bytes[0] = 0xFE;
foo.bytes[1] = 0x70;
}
else {
foo.bytes[1] = 0xFE;
foo.bytes[0] = 0x70;
}
bool shouldBeTrue = foo.value == -400;
Run Code Online (Sandbox Code Playgroud)
更新 - 更新.此解决方案适用于big-endian和little-endian计算机.谢谢你们πάνταῥεῖ.
在C#中,您可以使用BitConverter.GetBytes和BitConverter.ToInt16.要测试endianess,您可以检查BitConverter.IsLittleEndian.
应该在C,C++和C#(和可能的Java)中工作
short val;
val = (byte1 << 8) | byte2;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
228 次 |
| 最近记录: |