A Scripter's Notes

Emacs, scripting and anything text oriented.

Binary <> Decimal <> Hex conversion in Python

Python snippets to do number representation conversion among binary/decimal/hexadecimal.

  • Binary -> Decimal

    int('10010100', 2)
    
  • Hexadecimal -> Decimal

    int('94', 16)
    
  • Decimal -> Hexadecimal

    hex(148)[2:]
    

    The [2:] truncates the 0x prefix added to hex output string.

  • Decimal -> Binary

    bin(148)[2:]
    

    The [2:] truncates the 0b prefix added to binary output string.


Other conversions can be derived from the ones above.

  • Hexadecimal -> Binary

    bin(int('94', 16))[2:]
    
  • Binary -> Hexadecimal

    hex(int('10010100', 2))[2:]
    

Comments

comments powered by Disqus