user2793162
user2793162

Reputation:

Confused about htonl output

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?

Upvotes: 0

Views: 287

Answers (2)

MOHAMED
MOHAMED

Reputation: 43518

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

Upvotes: 2

Sergey L.
Sergey L.

Reputation: 22542

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

Upvotes: 1

Related Questions