C 从字节到DWORD的转换

C 从字节到DWORD的转换,c,winapi,C,Winapi,我已经编写了一个将ip转换为十进制的代码,它似乎给出了一个意外的结果,这是因为从字节到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*25

我已经编写了一个将ip转换为十进制的代码,它似乎给出了一个意外的结果,这是因为从字节到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。

即使
DWORD
是未签名的,您也会将其打印出来,就像它已签名一样(
%d
)。请尝试
%u

您的转换可能是正确的,但printf语句不是

使用
%u
”而不是
%d

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

您可以这样做:

DWORD dec = 0;
BYTE *pdec = (BYTE *)&dec;
pdec[0] = a;
pdec[1] = b;
pdec[2] = c;
pdec[3] = d;
#包括
内部主(空)
{
短a[]={0x11,0x22,0x33,0x44};
int b=0;

b=(a[0]首先发布您的实际代码,因为您在这段代码中犯了错误,例如printf中的dec是什么?其次,您可能希望在printf中使用“%u”
#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;
}