Benjamin Esham

Converting to and from hexadecimal at the command line

As a programmer1 I frequently need to convert numbers to or from their hexadecimal representations. Today I added the following functions to my zshrc:

function from_hex() {
    python -c "print(0x$1)"
}

function to_hex() {
    python -c "print('{:x}'.format($1))"
}

These aliases allow me to do conversions like

$ to_hex 42
2a
$ from_hex 09f91102
167317762

right from the command line. The code above works with GNU bash and with zsh.

(These functions inject unsanitized text into Python expressions, so they’re not very robust. Caveat emptor. I’m sure this is possible with shell built-ins too, but after a decade of not quite consciously realizing that I didn’t have a quick way to do these conversions, it felt good to fix the problem with a pair of one-liners that I could just type off the top of my head.)

  1. Honestly, I mostly encounter hexadecimal in CSS colors. I don’t do any numerical programming. ↩︎