Search code examples
cmathbit-manipulationrepresentation

C - Fast conversion between binary and hex representations


Reading or writing a C code, I often have difficulties translating the numbers from the binary to the hex representations and back. Usually, different masks like 0xAAAA5555 are used very often in low-level programming, but it's difficult to recognize a special pattern of bits they represent. Is there any easy-to-remember rule how to do it fast in the mind?


Solution

  • Each hex digit map exactly on 4 bit, I usually keep in mind the 8421 weights of each of these bits, so it is very easy to do even an in mind conversion ie

    A = 10 = 8+2 = 1010 ... 5 = 4+1 = 0101

    just keep the 8-4-2-1 weights in mind.

    A        5     
    8+4+2+1  8+4+2+1
    1 0 1 0  0 1 0 1