Romeo Romeo - 2 months ago 10x
Python Question

python convert hex string to formated binary string

From input


I need to output:

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
. I need a
between nibbles.

Thank you.


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

hex2bin_map = {
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)