Warm tip: This article is reproduced from serverfault.com, please click

integer-在联合C中打印int的字节

(integer - Printing bytes of int in union C)

发布于 2020-11-30 20:24:48

当数字255必须为255而不是-1时,如何打印int的字节?我可以看到,当我scanf 128时,我的程序打印-128,但是当我scanf 127时,我的程序打印127。我该怎么做,将printf 128做为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;
     }
Questioner
ResCrove
Viewed
0
dbush 2020-12-01 04:30:04

tab字段的类型更改unsigned char然后它们将具有正确的值。

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