Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Converting uint_32_t to network-byte-order results in shorter bit length than expected

I’m trying to convert an uint_64_t to network-byte-order, in order to do so, I’m splitting the uint_64_t into two uint_32_t in order to use htonl, since it can only be used with uint_32_t. I’m splitting it in the following manner:

uint32_t partA = (uint32_t) (x);
uint32_t partB = (uint32_t) (x >> 32);

when I enter for example x=1, I correctly get partA=1, partB=0, which makes perfect sense:

1 -> [00000000000000000000000000000000][00000000000000000000000000000001]

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Now, I decided to apply ntohl to each individual part like so:

uint32_t partA = htonl((uint32_t) (x));
uint32_t partB = htonl((uint32_t) (x >> 32)));

I would expect that partA should contain the bits the other way around (big endian), so it should hold the value 10000000000000000000000000000000 (32b), but instead, the value is 1000000000000000000000000 (25b), 7b shorter than it should be.

>Solution :

Byte order is applied to bytes, not bits.

1 is expressed in bytes 0x01 0x00 0x00 0x00 (little-endian) or 0x00 0x00 0x00 0x01 (big-endian).

Expressed in bits, they are 00000001 00000000 00000000 00000000 and 00000000 00000000 00000000 00000001.

The former 00000001 00000000 00000000 00000000 has 7 trailing zeros, so removing these zeros results in 7 bits shorter result.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading