Reputation: 2635
I have written a code to convert ip to decimal and it seems to give an unexpected results , this is because of conversion mismatch from BYTE to DWORD .
Is there a way to convert byte variable to word , the typecast doesn't seem to work .
Here is the portion of the code
//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);
}
I'm getting the value as -1062731519 instead of 3232235777 .
Upvotes: 0
Views: 3342
Reputation: 1
#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;
}
Upvotes: 0
Reputation: 763
You can do like this:
DWORD dec = 0;
BYTE *pdec = (BYTE *)&dec;
pdec[0] = a;
pdec[1] = b;
pdec[2] = c;
pdec[3] = d;
Upvotes: 2
Reputation: 608
Try the MAKEWORD()
macro. But using %d in printf will still give you a wrong output.
Upvotes: 2
Reputation: 5722
Your conversion is probably right, but your printf statement is not.
Use "%u
" instead of "%d"
.
Upvotes: 3
Reputation: 500893
Even though DWORD
is unsigned, you are printing it out as if it were signed (%d
). Try %u
instead.
Upvotes: 3