繁体   English   中英

将四个 8 位无符号整数组合成 32 位无符号 integer 但结果为负

[英]Combine four 8-bit unsigned integers into 32-bit unsigned integer but value is resulting negative

/程序将四个 8 位无符号整数组合成一个 32 位 integer 使用位移运算 预期结果为 4,294,967,295 Output 结果为 -256 /

#include <stdio.h>

int main()
{
    unsigned int a, b, c, d;
    printf("Enter number of IP address to form a.b.c.d \n");
    scanf("%i", &a);
    printf("a= %d\n",a);
    
    scanf("%i", &b);
    printf("b= %d\n",b);
    
    scanf("%i", &c);
    printf("c= %d\n",c);
    
    scanf("%i", &d);
    printf("d= %d\n",d);
    
    unsigned int  arr[]={a, b, c, d};
    unsigned int temp = 0;
    printf("\nIP address entered is %d.%d.%d.%d\n", arr[0], arr[1], arr[2], arr[3]);

    for(int i=0; i<4; i++)
    {
        printf("%dth value %i\n", i, arr[i]);
        printf("%i\n", temp);
        temp = temp | arr[i];
        temp = (unsigned int)temp<<0x8;
    }
    printf("\nThe actual value of IP address %d.%d.%d.%d is %i", a,b,c,d,temp);//32-bit string output is -256
    return 0;
}

您可以使用 printf 中的定义快捷方式尝试使用 %lu 或 %iu 打印它以表示无符号。


#define TOLONG(a,b,c,d) ((unsigned long)(a<< 24) | (b<< 16) | (c<< 8) | d)

temp = TOLONG(a,b,c,d);

printf("\nThe actual value of IP address %d.%d.%d.%d is %iu", a,b,c,d,temp);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM