Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Encoding of ... some sort?

Tags:

hex

encoding

Forgive me if this has been asked before, but I assure you I've scoured the internet and have turned up nothing, probably because I don't have the right terminology.

I would like to take an integer and convert it to a little-endian(?) hex representation like this:

303 -> 0x2f010000

I can see that the bytes are packed such that the 16's and 1's places are both in the same byte, and that the 4096's place and 256's place share a byte. If someone could just point me to the right terminology for such encoding, I'm sure I could find my answer on how to do it. Thanks!

like image 898
Blumer Avatar asked Oct 15 '22 15:10

Blumer


2 Answers

use bit shift operators combined with bitwise AND and OR operators...

assuming 32 bit unsigned:

int value = 303;
int result = 0x00000000;

for (int i = 0; i < 4; i++)
{
    result = result | ((value & (0xFF << (i * 8))) << (24 - (i * 8)));
}
like image 134
Demi Avatar answered Oct 20 '22 16:10

Demi


Big-endian and little-endian refer to the order of the bytes in memory. A value like 0x2f100000 has no intrinsic endianness, endianness depends on the CPU architecture.

If you always want to reverse the order of the bytes in a 32-bit value, use the code that Demi posted.

If you always want to get the specific byte order (because you're preparing to transfer those bytes over the network, or store them to a disk file), use something else. E.g. the BSD sockets library has a function htonl() that takes your CPU's native 32-bit value and puts it into big-endian order.

If you're running on a little-endian machine, htonl(303) == 0x2f100000. If you're running on a big-endian machine, htonl(303) == 303. In both cases the result will be represented by bytes [0x00, 0x00, 0x01, 0x2f] in memory.

like image 40
Marius Gedminas Avatar answered Oct 20 '22 16:10

Marius Gedminas