Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 667
psihodelia Avatar asked Dec 22 '22 02:12

psihodelia


2 Answers

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
like image 160
Felice Pollano Avatar answered Dec 30 '22 21:12

Felice Pollano


I always find easy to map HEX to BINARY numbers. Since each hex digit can be directly mapped to a four digit binary number, you can think of:

> 0xA4 

As

> b 1010 0100
>   ---- ---- (4 binary digits for each part)
>     A    4
like image 21
Pablo Santa Cruz Avatar answered Dec 30 '22 22:12

Pablo Santa Cruz