Quick tip – Binary to HEX and DEC conversion

I’ve been doing some work on the code, mostly involving i2c commands and addresses. Those are usually given in Hex in the datasheet, sometimes with binary reference, but you might find yourself needing to convert between the two and sometimes to Decimal.

There is a quick way to convert back and forth between all of them by hand with nothing but a piece of paper (you can do it in your head if you are good with numbers – I’m very bad at it :))

Anyway it’s a good old trick but it works.

The trick is that every bit has its own value, both in Hex and in Dec, adding (or substracting them – will give you the correct value)

it’s best when drawn to a table:

DEC 128 64 32 16 8 4 2 1
HEX 0x80 0x40 0x20 0x10 0x08 0x04 0x02 0x01
BIN

let’s take for example a 7 bit i2c address, specific chip datasheet will tell you that the address is something like

0 1 0 0 A2 A1 A0

which is kinda usless let’s convert it to hex (which makes more sense).
lets just assume that all the Address pins are 0
so it’s just the 6th position bit set, which is 0x20.

now let’s look on the other end, where the address pins are all 1.
that is :

0 1 0 0 1 1 1

so we have our 0x20 in addition to 0x01, 0x02 and 0x04
it’s simple math at this point, 0x27.
Only thing to remember that HEX is base 16, so 0x08+0x04 is not 0x12 but rather 0x0C

it’s also useful for slightly different scenarios,
the commands for this chip are also 7 bits, and the datasheet specify 0x18 as the command for a output write to bank0, but it also gives you the option to AutoIncrement the used data banks. this is done by adding a leading 1 in the byte. (in the MSB).
this we know to be 0x80. so to write incrementally starting from bank0 command is 0x98.

Decimal is pretty much the same thing.
let’s use the same 0x27 example
in Dec its 32+4+2+1 = 39

And that’s it 🙂

Leave a Reply