字节签名短

Roo*_*Roo 0 c# c++

我得到两个字节,例如0xFE和0x70,它应该代表-400的值.我怎么能把这些字节转换成有符号的短?它甚至可能吗?

Mar*_*nko 6

在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.GetBytesBitConverter.ToInt16.要测试endianess,您可以检查BitConverter.IsLittleEndian.

  • 请注意提及此解决方案的endianess陷阱. (3认同)

Ric*_*der 6

应该在C,C++和C#(和可能的Java)中工作

 short val;
 val = (byte1 << 8) | byte2;
Run Code Online (Sandbox Code Playgroud)