开发者

Byte numbering question

In this byte formula

y=(((x[0]<<8)+x[1])*1);

would x[0] refer to the left most byte or the right most byte?

Lets say in Hex the number x 开发者_如何学编程was 10DF, what would the result be?


x[0] refers to the leftmost byte in the number, i.e. the one closer to the beginning of the address space.

If those two bytes contain the number 0x10DF, x[0] is 0xDF if the system is little endian and 0x10 if the system is big endian. If we assume that bit of code is just trying to extract the number from memory, I'd imagine that the number in memory is big endian because it's left-shifting (multiplying) the first byte, meaning it's more significant.


<< is shift left operator, so obviously x[0] is moving left here. It would be the 0x10 of 0x10DF.

edit

To clarify - I assume that 0x10DF is the value of the result - y.


Assuming that x was a multi-byte value, the `leftness' of x (or more precisely its significance) is dependent on the endianness of whatever architecture you are using:

http://en.wikipedia.org/wiki/Endianness

On x86, the higher address byte is the more significant value.

EDIT: Thanks to Rob for spotting the typo earlier


Endianness is not immediately an issue, because no pointer casting is involved. Suppose we have:

unsigned char x[] = { 0xAB, 0xEF };

Then the following algebraic expression is completely portable and representation-independent:

unsigned int y = (x[0] << 8) + x[1]

The result will always be y == 0xABEF. (Let's assume that we have CHAR_BITS == 8.)

It is an entirely different matter how this is layed out in memory, which does depend on the machine endianness. This information is accessible through type punning:

uint16_t z = *(uint16_t*)(x);

Now in memory z is layed out as AB EF, whatever that means: 0xABEF on big- and 0xEFAB on little-endian systems.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜