Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How will this code will work on a big endian machine?

Tags:

c

endianness

If I have the code:

uint64_t a = 0x1111222233334444;
uint32_t b = 0;
b = a;
printf("a is %llx ",a);
printf("b is %x ",b);

and the output is :

 a is 1111222233334444 b is 33334444

Questions :

  1. Will the behavior be same on big-endian machine?

  2. If I assign a's value in b or do a typecast will the result be same in big endian?

like image 628
Jeegar Patel Avatar asked Sep 01 '11 05:09

Jeegar Patel


2 Answers

The code you have there will work the same way. This is because the behavior of downcasting is defined by the C standard.

However, if you did this:

uint64_t a = 0x0123456789abcdefull;
uint32_t b = *(uint32_t*)&a;
printf("b is %x",b)

Then it will be endian-dependent.

EDIT:

Little Endian: b is 89abcdef

Big Endian : b is 01234567

like image 75
Mysticial Avatar answered Oct 21 '22 20:10

Mysticial


When assigning variables, compiler handles things for you, so result will be the same on big-endian.

When typecasting pointers to memory, result will NOT be the same on big-endian.

like image 1
hamstergene Avatar answered Oct 21 '22 19:10

hamstergene