开发者

Getting the least significant byte

I haven't tested on a big endian processor but would this alway开发者_开发问答s give me least significant byte?

int i = 12345678;
unsigned char c = static_cast<unsigned char>(i);


Yes, this will always give you the least-significant byte. The C++ spec (§4.7/2) guarantees that narrowing conversions always discard the most-significant bytes by giving back the smallest value congruent to the original integer, modulo 2n, where n is the number of bits in the target type.

That said, there's no guarantee that an unsigned char is a single byte. All that's guaranteed is that sizeof(char) == 1. However, if you treat a byte as the smallest memory unit capable of holding a character, then this should work just fine.


Wouldn't the following also work?

int i = 12345678;
unsigned char c = (i % 256);

or

int i = 12345678;
unsigned char c = (i & 255);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜