Romeo Romeo - 3 months ago 25
Python Question

python convert hex string to formated binary string

From input

0x1234

I need to output:
0b0001_0010_0011_0100
.

I can think of all the bad ways to do this, but what's the most pythonic way to achieve this.

I can easily convert to bin string
(bin(int('0x1234', 16))
, but that only gives me
0001001000110100
. I need a
_
between nibbles.

Thank you.

Answer

hex maps one digit to one nibble ... so you can do it quite easily with a lookup table

hex2bin_map = {
   "0":"0000",
   "1":"0001",
   "2":"0010",
   "3":"0011",
   "4":"0100",
   "5":"0101",
   "6":"0110",    
   "7":"0111",
   "8":"1000",
   "9":"1001",
   "A":"1010",
   "B":"1011",
   "C":"1100",
   "D":"1101",
   "E":"1110",
   "F":"1111",
}
hex_num="1234"
print "_".join(hex2bin_map[i] for i in hex_num)
# 0001_0010_0011_0100

this isnt as terse as the other answer(s) im sure ... but its probably the most performant ... and its pretty dang easy to read (ie you dont need to worry about the grouper pattern of zip, nor regex's, which are bound to confuse newer programmers)