views:

105

answers:

3

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!

+2  A: 

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)));
}
Demi
Thanks, Demi. I don't think this ended up being quite what I needed, but probably more because I didn't quite describe the problem fully.
Blumer
@Blumer: your code snippet in vb does essentially the same thing, only with a slightly different order of operations and with integer division instead of bit operations. You are essentially byte swapping byte 0 with byte 3, and byte 1 with byte 2
Demi
+2  A: 

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.

Marius Gedminas
A: 

If anyone can put a specific term to what I was trying to do, I'd still love to hear it. I did, however, find a way to do what I needed, and I'll post it here so if anyone comes looking after me, they can find it. There may be (probably is) an easier, more direct way to do it, but here's what I ended up doing in VB.Net to get back the bytecode I wanted:

Private Function Encode(ByVal original As Integer) as Byte()    
    Dim twofiftysixes As Integer = CInt(Math.Floor(original / 256))
    Dim sixteens As Integer = CInt(Math.Floor((original - (256 * twofiftysixes)) / 16))
    Dim ones As Integer = original Mod 16
    Dim bytecode As Byte() = {CByte((16 * sixteens) + ones), CByte(twofiftysixes), 0, 0}
    Return bytecode
End Function

Effectively breaking the integer up into its hex components, then converting the appropriate pairs to cBytes.

Blumer