在 C++ 中,有符号短到字节

signed short to byte in c++

本文关键字:符号 到字节 C++      更新时间:2023-10-16

我正在尝试使用 C++ 将十六进制数转换为短(2 字节)一切都很好,除了一件事...从短到字节的有符号转换(上次测试)

我发现了这个问题,但无法真正从中受益:可移植的有符号/无符号字节转换,C++

以下是我的测试:

// test 1 - positive B2Short (success)
byte *b = new byte[2];
b[0] = 0x10; //low byte
b[1] = 0x00; //heigh byte
signed short test = 0;
test = ByteToShort(b);
cout << test << endl;
// test 2 - negative B2Short (success)
b[0] = 0xF0; //low byte
b[1] = 0xFF; //heigh byte
test = 0;
test = ByteToShort(b);
cout << test << endl;
// test 3 - positive Short2B (success)
signed short n = 11;
ShortToByte(n, b);
test = ByteToShort(b);  // for display to see if it worked
cout << test << endl;
// test 4 - negative Short2B (FAIL!)
n = -11;
ShortToByte(n, b);
test = ByteToShort(b);  // for display to see if it worked
cout << test << endl;

使用的功能:

signed short ByteToShort(byte* bytes){
    signed short result = 0;
    result = (result<<8) + bytes[1]; // heigh byte
    result = (result<<8) + bytes[0]; // low byte
    return result;
}
void ShortToByte(signed short num, byte* bytes){
    bytes[1] = num & 0xFF00; // heigh byte
    bytes[0] = num & 0x00FF; // low byte
}

输出:

16
-16
11
245

ShortToByte

bytes[1] = num & 0xFF00; // high byte

您必须将其移动到正确的 8 位,以使结果适合一个字节。否则,您将只从低部得到零。

我会说使用联合会容易得多:

union ShortByteUnion {
    signed  short asShort;
    unsigned char asBytes[2];
};

它会为您处理转换。

只需将短数组转换为字节数组。

signed short test = 1234;
byte* b;
b = (byte*) &test;
b[0];//one byte
b[1];//another byte

在多种类型的机器上执行此操作是很危险的事情,因为字节序可能会有所不同。

我不喜欢单行,但它们在这里:

((byte*)&test)[0];
((byte*)&test)[1];