c - 理解 C 中的无符号 0

标签 c

我正在尝试理解 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/

相关文章:

c++ - 编写符合严格别名的 memcpy

c++ - 将事件设置为零的文件描述符添加到 epoll 是否有效?

c - 返回 float 的指数值

c - 如何在C中搜索图结构中的特定节点?

c - 如何用C语言画一个不同符号和对角线的正方形?

c - 如果我使用 select() 服务器编写一个对等 2 个对等应用程序而不使用 fork()、线程、共享内存、信号量,这样可以吗?

c - 如何修复 "expected ' )' before ' ['

c - 为什么在 select 中使用 writefds ?如何在实践中使用它们?

捕捉奇怪的 C 指针算术错误

c - 平衡工作负载分配?