c-从字节到DWORD的转换



我写了一个代码将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);
}

我得到的值是-1062735119,而不是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;
#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("nnValue of B is %x", b);
    return 0;
}

最新更新