从BYTE转换为DWORD

时间:2013-07-10 06:00:24

标签: c winapi

我编写了一个将ip转换为十进制的代码,它似乎给出了意想不到的结果,这是因为从BYTE到DWORD的转换不匹配。

有没有办法将字节变量转换为单词,类型转换似乎不起作用。

这是代码的一部分

  //function to convert ip 2 decimal 
   DWORD ip2dec(DWORD a ,DWORD b,DWORD c,DWORD d)
   {  

     DWORD dec;
     a=a*16777216;
     b=b*65536;
     c=c*256;
     dec=a+b+c+d;

     return dec;

  }

int main()
{
   BYTE a,b,c,d;
   /* some operations to split the octets and store them in a,b,c,d */
   DWORD res=ip2dec(a,b,c,d);
   printf("The converted decimal value = %d",dec);
}

我的值为-1062731519而不是3232235777.

5 个答案:

答案 0 :(得分:4)

即使DWORD未签名,您也会将其打印出来,就像签名一样(%d)。请改为%u

答案 1 :(得分:3)

您的转换可能是正确的,但您的printf声明不是。

使用"%u“代替"%d"

答案 2 :(得分:2)

尝试使用MAKEWORD()宏。但是在printf中使用%d仍然会给你一个错误的输出。

答案 3 :(得分:2)

你可以这样做:

DWORD dec = 0;
BYTE *pdec = (BYTE *)&dec;
pdec[0] = a;
pdec[1] = b;
pdec[2] = c;
pdec[3] = d;

答案 4 :(得分:0)

#include  <stdio.h>

int main(void)
{

    short a[] = {0x11,0x22,0x33,0x44};
    int b = 0;

     b = (a[0] << 24 ) | ( a[1] << 16 ) | (a[2] << 8 ) | ( a[3] );

    printf("Size of short  %d \nSize of int  %d ", sizeof(short), sizeof(int));

    printf("\n\nValue of B is %x", b);
    return 0;
}
相关问题