Mike
Mike

Reputation: 1

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?

Upvotes: 0

Views: 151

Answers (4)

Kerrek SB
Kerrek SB

Reputation: 476950

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.

Upvotes: 1

Mikola
Mikola

Reputation: 9326

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

Upvotes: 1

littleadv
littleadv

Reputation: 20262

<< 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.

Upvotes: 1

Matti Virkkunen
Matti Virkkunen

Reputation: 65116

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.

Upvotes: 2

Related Questions