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)'

And back again:

python -c 'print hex(127)

For floats you can use the float.hex method:

python -c 'print float.hex(120.5)'

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


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