在联合 C 中打印 int 字节

Printing bytes of int in union C

当数字 255 必须是 255 而不是 -1 时,如何打印 int 字节? 我可以看到,当我扫描 128 时,我的程序打印 -128,但是当我扫描 127 时,我的程序打印 127。 我能做什么 printf 128 as 128.

    #include <stdio.h>
    union byte_set{
    int x;
    char tab[4];
    };
    int main(){
         union byte_set byte_set;
        printf("Podaj liczbe: ");
        if(scanf("%d", &byte_set.x) != 1)
        {
            printf("Incorrect input");
            return 1;
        }
        for(int i = 0; i < 4; i++)
        {
        printf("%02d ", *(byte_set.tab+i));
        }
        return 0;
     }

tab 字段的类型更改为 unsigned char。然后他们就会有正确的值。

union byte_set{
    int x;
    unsigned char tab[4];
};