Why does not uint16_t show the desired output?

161 views Asked by At

I have an array-

uint8_t arrayTest[] = {
    0, 0xC1,                
    0, 0, 0, 0x0a,          
    0, 0, 0, 0x50           
 };

So the following printf with uint32_t shows the correct output "a":

printf("%x ",ntohl(*((uint32_t *)(arrayTest+2))));

But uint16_t does not show it correctly, although I forward the array pointer two fields, the output is "a0000"-

printf("%x ",ntohl(*((uint16_t *)(arrayTest+4))));

It is same when I use %d:

With printf("%d ",ntohl(*((uint32_t *)(arrayTest+2)))); the output is "10"

With printf("%d ",ntohl(*((uint16_t *)(arrayTest+4)))); the output is "655360"

Why???

1

There are 1 answers

0
MvG On BEST ANSWER

nothl is only for converting 32bit quantities. It will produce incorrect result for 16bit quantities, at least on little endian systems. Use ntohsfor that.