language-agnosticnumbershexbytebit-manipulation

How do you split a hex string into bytes?


Because hex is often used to represent things like RGBA color model data, I'm trying to find out how to go about taking a large hex string like 0x11AA22BB and split it into separate bytes. (So; 0x11, 0xAA, 0x22, and 0xBB chunks, essentially..). I know that each hex digit can be directly represented by four bits. But breaking up a chain of bits into smaller groups isn't something that I know how to do, either.

So, I'm sure that there is probably a simple answer to this. I'm sure it probably has something to do with casting it to an array of single bytes, or using bitwise operators or something, but I can't figure it out. I know that there is also an issue of endianness and how the bytes are organizes (RGBA, ARBG, ABGR, etc.), but right now I'm just looking to understand how to do the splitting so I can get a general understanding of how it works. I'm using C++ but I think that this might not necessarily be specific to that language.

So, to reiterate; How does one take a large hex string like 0x11AA22BB and split it into 0x11, 0xAA, 0x22, 0xBB?


Solution

  • The two ways are mod/div and shift/mask, but both are actually the same way.

    mod/div:

    num = 0x11aa22bb
    while num > 0:
      byte = num % 0x100
      print hex(byte)
      num //= 0x100
    

    shift/mask:

    num = 0x11aa22bb
    while num > 0:
      byte = num & 0xff
      print hex(byte)
      num >>=8