C - fast conversion between binary and hexadecimal representations

Reading or writing C code, I often have difficulty translating numbers from binary to hexadecimal and vice versa. Typically, various masks, such as 0xAAAA5555 , are very often used in low-level programming, but it is difficult to recognize the particular set of bits that they represent. Is there any catchy rule on how to do this quickly in the mind?

+4
source share
3 answers

Each card with a hexadecimal digit is exactly 4 bits, I usually remember 8421 the weights of each of these bits, so it’s very easy to even make a conversion in mind, i.e.

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

just keep the scales 8-4-2-1 .

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

It is always easy for me to match HEX with binary numbers. Since each hexadecimal digit can be directly mapped to a four-digit binary number , you can think of:

 > 0xA4 

how

 > b 1010 0100 > ---- ---- (4 binary digits for each part) > A 4 
+3
source

The conversion is calculated by dividing the base 10 representation by 2 and applying the remainder in the reverse order. I do it in my head, it seems to work.

So you say what 0xAAAA5555 looks 0xAAAA5555

I just understand how A looks and 5 looks by doing

 A = 10 10 / 2 = 5 r 0 5 / 2 = 2 r 1 2 / 2 = 1 r 0 1 / 2 = 0 r 1 

so I know that A looks like 1010 (note that 4 fingers is a good way to remember leftovers!)

You can group 4-bit blocks together, so AA is 1010 1010. To convert the binary back to hex, I go back to base 10 again, adding authority 2. You can do this by forming blocks of 4 bits (padding with 0s ) and a string of results.

therefore, 111011101 is 0001 1101 1101 , which is (1) (1 + 4 + 8) (1 + 4 + 8) = 1 13 13 , which is 1DD

0
source

Source: https://habr.com/ru/post/1396434/


All Articles