سؤال

I have simple question. This code:

   int t = 1;

   int y = htonl(t);
   printf("Y = %d, sizeof(int)=%d", y, sizeof(int));

prints

Y = 16777216, sizeof(int)=4

On a little endian machine (it is online compiler actually).

I was expecting y to be number (in binary): 1000....000 (0 - 31 times).

But 16777216 has only roughly 25 zeros next to 1 (in binary).

What did I miss?

هل كانت مفيدة؟

المحلول

int t = 1;

In memory (for 4 byte systems) is presented in this way

 ---------------
| 0 | 0 | 0 | 1 |
 ---------------
  ^            ^
  | byte       | = 0x1 = 00000001 in binary

The binary format is

00000000 00000000 00000000 00000001 

htonl() allow to reverse the bytes if your system is a little endian system

so htonl(t) will return:

 ---------------
| 1 | 0 | 0 | 0 |
 ---------------
  ^
  | = 0x1 = 00000001 in binary

so the whole htonl(t) in binary is

00000001 00000000 00000000 00000000

equal to 16777216 in decimal

نصائح أخرى

It did exactly what you ask it to.

Your output in hex is 01 00 00 00. htonl on little endian swaps bytes around, not bits.

16777216 = 0x01000000
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top