我正在尝试理解 C 中的数字表示。 我正在编写一个代码段,如下所示。
#include <stdio.h>
#include <string.h>
typedef unsigned char *byte_pointer;
void show_bytes(byte_pointer start, int len)
{
int i;
for (i = 0; i < len; i++)
printf(" %.2x", start[i]);
printf("\n");
}
void show_int(int x) {
show_bytes((byte_pointer) &x, sizeof(int));
}
void show_unsigned(short x) {
show_bytes((byte_pointer) &x, sizeof(unsigned));
}
int main(int argc,char*argv[])
{
int length=0;
unsigned g=(unsigned)length;// i aslo tried with unsigned g=0 and the bytes are the same
show_unsigned(g);
show_int(length);
printf("%d",g);//this prints 0
return 0;
}
这里,show_unsigned()
和 show_int()
打印指定为参数的变量的字节表示形式。对于 int 长度,字节表示形式按预期全为零,但是对于无符号 g,字节表示为 00 00 04 08
。但是当我用 %d 打印 g 时,我得到 0(所以我认为数值被解释为 0 )
请有人解释一下这是如何发生的。
最佳答案
在:
void show_unsigned(short x) {
show_bytes((byte_pointer) &x, sizeof(unsigned));
}
您声明的参数 short x
小于 int x
,因此您忽略了一些 00
并且您的打印函数显示相邻垃圾。
关于c - 理解 C 中的无符号 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18517407/