问题描述
我不明白为什么下面的代码输出是0xffffffef ...而不是0xef。请帮助我理解这一点:
#include <stdio.h>
main()
{
int i;
int n = 4;
char txBuff = 0;
long Data_b = 0xABCDEF;
int y = sizeof(txBuff);
printf("%d\n",y);
txBuff = (Data_b & 0xff);
for(i=0; i<n; i++)
{
txBuff = (Data_b & 0xff);
// txBuff= txBuff & 0xff;
Data_b = (Data_b >> 8);
printf("txBuff[%d]=%x,Data_b=%x \n",i,txBuff,Data_b);
}
}
输出:
1
txBuff[0]=ffffffef,Data_b=abcd
txBuff[1]=ffffffcd,Data_b=ab
txBuff[2]=ffffffab,Data_b=0
txBuff[3]=0,Data_b=0
解决方法
您使用错误的占位符进行打印:
getline(cin,fullName); // reads John Jacob Jingleheimer Schmidt into fullname,cout << fullName << endl; // prints John Jacob Jingleheimer Schmidt
当您错误地解释参数时,您将看到各种奇怪结果。
根据printf
notation,此处printf("txBuff[%d]=%hhx,Data_b=%lx \n",i,txBuff,Data_b);
表示“十六进制转储%hhx
”和unsigned char
表示“十六进制转储%lx
”。
unsigned long
值得抱怨的地方:
clang
,
进行位操作时使用无符号类型!
在
char txBuff = 0;
...
txBuff = (Data_b & 0xff);
txBuff
可以变为负数,并在int
调用中传播到printf()
。