Wednesday, November 20, 2013

Easily convert hex to ints and vice versa with python and the command line

I've started a lot of work lately with the ssd1306 oled display (which you can pick up for a few bucks on ebay) and my raspbery pi. While sending commands I've found it useful to be able to easily convert between ints and hexadecimal strings and back again.

To convert a hexadecimal value to an int on the command line:

python -c 'print int(0x7f)'
127

And back again:

python -c 'print hex(127)
0x7f

For floats you can use the float.hex method:

python -c 'print float.hex(120.5)'
0x1.e200000000000p+6

Maybe you want that trimmed:
python -c 'print float.hex(120.5)[:7]'

0x1.e20

It's worth noting that the '-c' flag being passed to python essentially tells python that the first argument is a script it should execute normally.

No comments:

Post a Comment