2

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???

rrsuj
  • 409
  • 6
  • 10
  • [The usual integral conversions](http://channel9.msdn.com/Series/C9-Lectures-Stephan-T-Lavavej-Core-C-/Stephan-T-Lavavej-Core-C-7-of-n)... – Kerrek SB Dec 18 '13 at 14:30
  • 3
    You are invoking **undefined behaviour** here (dereferencing through those pointer casts). – Oliver Charlesworth Dec 18 '13 at 14:30
  • `printf` is not a safe function. Be vewy vewy careful when using it. This includes [*reading the manual*](http://pubs.opengroup.org/onlinepubs/000095399/functions/printf.html). – Kerrek SB Dec 18 '13 at 14:31
  • 4
    Note that there's an ntohs() function for 16 bit data and ntohl() for 32 bit data. – nos Dec 18 '13 at 14:38

1 Answers1

1

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

MvG
  • 57,380
  • 22
  • 148
  • 276