原始c ++内存逻辑的奇怪行为

时间:2016-07-18 14:03:38

标签: c++ memory stm32 iar

在带有stm32(arm cortex)CPU的IAR IDE中,我在原始情况下有非常奇怪的行为。

uint32_t s = 6654; //=0x000019FE
//next I'll see in IAR debugger

uint8_t res1 = 0;
res1 = (s&0xFF000000)>>24;  //see in debugger: res1=00
res1 = (s&0x00FF0000)>>16;  //res1=00
res1 = (s&0x0000FF00)>>8;   //res1=19
res1 = (s&0x000000FF);      //res1=FE

void *sp = &s;
uint8_t res2 = 0;
res2 = *((uint8_t*)sp+0);   //res2=FE            but must be 00!
res2 = *((uint8_t*)sp+1);   //res2=19            but must be 00!
res2 = *((uint8_t*)sp+2);   //res2=00            but must be 19!
res2 = *((uint8_t*)sp+3);   //res2=00            but must be FE!

(请参阅我期望的评论,以及会发生什么。) 为什么我得到这个结果?我没有解释。

1 个答案:

答案 0 :(得分:9)

你平台的 endianness 会让你感到困惑:你期待一个 Big endian 模型,你通过调试器观察到的是 Little endian

本文可能有所帮助:Endianness - Wikipedia, the free encyclopedia