在c ++中签名short to byte

use*_*945 0 c++ byte short

我正在尝试使用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;
Run Code Online (Sandbox Code Playgroud)

使用的功能:

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
}
Run Code Online (Sandbox Code Playgroud)

输出:

16
-16
11
245
Run Code Online (Sandbox Code Playgroud)

Bo *_*son 9

来自ShortToByte:

bytes[1] = num & 0xFF00; // high byte
Run Code Online (Sandbox Code Playgroud)

您必须将此位移到右侧8位才能使结果适合一个字节.否则你只会从低部分得到零.


Ric*_*III 7

我会说使用联合会更容易:

union ShortByteUnion {
    signed  short asShort;
    unsigned char asBytes[2];
};
Run Code Online (Sandbox Code Playgroud)

它会为您完成转换.