I'm new on C programming and I'm testing some code where I receive and process an UDP packet formatted as follow:
UINT16 port1
UINT16 port2
The corresponding values on this test are:
6005
5555
If I print the whole packet buffer I get something like this:
u^W³^U><9e>^D
How can I break it and get the right values? I've tried uint16_t
and unsigned short
and even the function htons
, but didn't work either I just get wrong numbers, I'm trying something like this:
int l = 0;
unsigned short *primaryPort = *(unsigned short*) &buffer[l];
AddToLog(logInfo, "PrimaryPort: %u\n", primaryPort);
l += sizeof(*primaryPort);
unsigned short *secondaryPort = *(unsigned short *) &buffer[l];
AddToLog(logInfo, "SecondaryPort: %u\n", secondaryPort);
l += sizeof(*secondaryPort);
What is the right or the best way to get these values? I think these two uint16 values are not integer formatted, I think it's just an uint16
char text on this characters u^W³^U><9e>^D
, so perhaps I'm getting the wrong numbers because I'm processing like an integer. But I've tried everything and I just can't get the right values.
When I look at the buffer you receive, it indeed starts with 6005 (little Endian):
6005 is 0x1775 and the first two characters are u
(0x75) and Ctrl-W
(0x17). So you should get the int value by:
unsigned short primaryPort = (buffer[l] & 0xff) | ((buffer[l+1] & 0xff) << 8 );
and the same for the secondary port.
Edit
It works because:
In an expression like buffer[l] & 0xff
, buffer[i]
is implicitly casted into an int
(search for 'integer promotion' to learn more). Masking it with 0xff
is neccessary if buffer
is char *
: Then buffer[i]
is a signed char and thus, if the highest bit is set, it's value is negative (e.g. '\xff'
is -1). Masking it makes sure that we get a positive value in the range 0 - 255 instead. Last but not least, the shift operator << 8
shifts the byte value to the next higher byte the calculated int
. Finally the result of the complete operation is implicitly casted to unsigned short
which can be done safely because the calculated int
is less or equal to 0xffff.