signed short to byte in c++

邮差的信 提交于 2019-12-19 12:23:45

问题


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)

i found this question and couldn't really benefit from it: portable signed/unsigned byte cast,C++

here are my tests:

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

functions used:

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
}

outputs:

16
-16
11
245

回答1:


From ShortToByte:

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

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.




回答2:


I'd say this would be much easier using a union:

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

It takes care of the conversion for you.




回答3:


Just cast the short to byte array.

signed short test = 1234;
byte* b;

b = (byte*) &test;

b[0];//one byte
b[1];//another byte

It's dangerous thing to do this on more than one types of machine, because endianess may vary.

I don't like one-liners, but here they go:

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


来源:https://stackoverflow.com/questions/10288109/signed-short-to-byte-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!