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

爷,独闯天下 提交于 2019-12-10 14:46:30

问题


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?


回答1:


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




回答2:


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.




回答3:


direct assignment will yield the same result on both little endian and big endian.

memory typecast on big endian machine will output

a is 1111222233334444 b is 11112222



来源:https://stackoverflow.com/questions/7266332/how-will-this-code-will-work-on-a-big-endian-machine

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!