2

I'm trying to read individual bytes of an int in C, but for some reason the following happens:

int x = -128; //this prints 128 255 printf("%d %d\n", ((unsigned char *) (&x))[0], ((unsigned char *) (&x))[3]); 

Should it not print 128 128 instead?

1
  • 1
    What kind of computer are you on? Little endian? Big endian? Commented Apr 1, 2014 at 5:11

3 Answers 3

2

The representation of -128 in two's complement is

11111111 11111111 11111111 10000000 // 4 bytes 

The endianness of a system means the order in which the bytes are stored in memory. Big-endian means that most significant byte, i.e., the first byte, is stored in the smallest address and little endian means that the least significant byte, i.e., the last byte is stored in the smallest address. Your machine is little endian. Therefore, the order of bytes is

10000000 11111111 11111111 11111111 // 4 bytes 

Therefore, ((unsigned char *) (&x))[0] means the first byte 100000000 and evaluates to 128. ((unsigned char *) (&x))[3] means the last byte 11111111 which evaluates to 255.

Sign up to request clarification or add additional context in comments.

Comments

2

It is machine specific and depends upon the endianness of the processor.

(look into the endianness wikipage, it is very well explained; x86-64 is little-endian.)

Comments

0
Should it not print 128 128 instead? 

-128 is represented as

11111111 11111111 11111111 10000000 [3] [2] [1] [0] 

when you say ((unsigned char *) (&x))[0] in case of little endian machine, it will print 128 cos you are trying to cast (10000000) to unsigned char which is 128 and (unsigned char *) (&x))[3] would print 255 which is all 1's.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.