当数字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;
}
将tab
字段的类型更改为unsigned char
。然后它们将具有正确的值。
union byte_set{
int x;
unsigned char tab[4];
};