signed short to byte in c++

六月ゝ 毕业季﹏ 提交于 2019-12-01 14:07:41
Bo Persson

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.

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.

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