0

I have following code:

int main ( void ) {
   unsigned int array [] = { 298 , 0 x1A2A3A4A };
   unsigned char *p = ( unsigned char *) array ;
   for (int i = 4; i < 8; i ++) {
       printf ("% hhX ", p[i]) ;
     }
   printf ("\ nThe Answer is %d or %d!\n", p[0] , p [6]) ;
   return EXIT_SUCCESS ;

 }

I dont understand the output:

4A 3A 2A 1A
The Answer is 42 or 42
  • 2
    You system is little endian so the bytes print backwards and your array value p[6] is 2A or 42 as decimal. p[0] is 42 because the top bits of 298 ironically, are also 2A. – Bayleef Dec 08 '19 at 15:06
  • [UINT16 value appears to be “backwards” when printing](https://stackoverflow.com/q/1288761/995714) – phuclv Dec 09 '19 at 07:59

1 Answers1

0

On a little endian system, the layout of the 8 byte array is

Position:     0 |  1 |  2 |  3 |  4 |  5 |  6 |  7
Value (Hex): 2A | 01 | 00 | 00 | 4A | 3A | 2A | 1A

Your loop prints the last 4 bytes in the order they appear in the array. Your final printf prints the values at the 0 and 6 position, which are both 0x2A, or 42 in decimal.

nickelpro
  • 2,537
  • 1
  • 19
  • 25