質問

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