在 C++ 中,有符号短到字节
signed short to byte in c++
我正在尝试使用 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];
相关文章:
- 获取隐式转换溢出从无符号到已签名的警告
- 使用 swig 追加到字节数组
- Ascii .txt文件到字节数组 - C++
- 将 CByteArray 复制到字节数组中会导致访问冲突
- 将HICON / HCURSOR复制到字节数组中
- 将 QImage 保存到字节数组
- 如何将数据复制到字节数组的某些部分
- 将数据流到字节数组中
- 如何将任何值转换为字节数组并将其附加到字节列表
- 以C++(Arduino)为单位比较指针到字节
- C++BigInteger到字节数组
- 从套接字到字节数组的读取数据中的意外字符
- C++结构到字节*引发错误
- std ::字符串到字节[]
- 如何从iStream的开头便移到字节中的偏移
- 将结构添加到字节向量,然后添加另一个
- crypto++将密钥保存到字节队列并返回到密钥
- std::wstring中ASCII符号的字节表示,具有不同的语言环境
- 高效的无符号到签名转换,避免实现定义的行为
- 在 C++ 中,有符号短到字节