在C ++中从短到字节签名 [英] signed short to byte in c++
本文介绍了在C ++中从短到字节签名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试使用C ++
将十六进制数转换为短整数(2字节),除一件事情外,其他都没问题...从短符号转换为字节(最后一次测试)
I'm trying to convert a HEX number into a short (2 Bytes) using C++ everything is OK except for one thing... signed conversion from short to Byte (last test)
我发现了这个问题,不能真正从中受益:便携式有符号/无符号字节转换,C ++
i found this question and couldn't really benefit from it: portable signed/unsigned byte cast,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位以使结果适合字节。否则,您只会从最低部分获得零。
You have to shift this to the right 8 bits for the result to fit in a byte. Otherwise you will just get the zeros from the low part.
这篇关于在C ++中从短到字节签名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文