#include <stdio.h> typedef unsigned char uint8_t; typedef unsigned int uint32_t; uint8_t buf3[] = {0x12,0x34,0x56,0x78}; int main() { // unexpected result uint32_t tick_num1 = buf3[0]<<8 + buf3[1]; printf("tick_num1 is:0x%x \n\r",tick_num1); uint32_t tick_num2 = (buf3[0]<<8) + buf3[1]; printf("tick_num2 is:0x%x \n\r",tick_num2); // unexpected result uint32_t tick_num3 = buf3[0] + buf3[1]<<8 + buf3[2]<<16 + buf3[3]<<24; printf("tick_num3 is:0x%x \n\r",tick_num3); // expected result uint32_t tick_num4 = buf3[3] + (buf3[2]<<8) + (buf3[1]<<16) + (buf3[0]<<24); printf("tick_num4 is:0x%x \n\r",tick_num4); return 0; }
➜ char_vs_int git:(master) ✗ ./test tick_num1 is:0x20000000 tick_num2 is:0x1234 tick_num3 is:0x0 tick_num4 is:0x12345678
建议吃不准的同学还是尽量加括号,这样才不至于犯大错。
原文链接:https://www.cnblogs.com/dylancao/p/17165159.html
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:c语言运算符优先级实例解析 - Python技术站