Bytes to signed short

本文关键字:short signed to Bytes | 更新日期: 2023-09-27 18:11:59

我得到两个字节,例如0xFE和0x70,它应该代表-400的值。如何将这些字节转换为有符号短字节?这可能吗?

Bytes to signed short

应该在C, c++和c#(可能还有java)中工作

 short val;
 val = (byte1 << 8) | byte2;

在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;

UPDATE-UPDATE 。这个解决方案对于大端和小端计算机都是正确的。感谢π α ντα ν

在c#中你可以使用BitConverter。GetBytes和BitConverter.ToInt16。要测试端序,可以检查BitConverter.IsLittleEndian.

这适用于c#:

byte[] arr = { 0xFE, 0x70 };
string hexStr = String.Join("", arr.Select(b => b.ToString("X")));
short res = Convert.ToInt16(hexStr, 16);
Console.WriteLine(res); // -400