To improve readability, I would like to print a binary number in groups of 4 (nibbles), that are separated by an underscore.
For example:
9 => "1001"
60 => "0011_1100"
100 => "0110_0100"
63000 => "1111_0110_0001_1000"
I was wondering if there was perhaps a simple way of doing this?
Splitting the logic into generating groups of 4 and joining.
def gen(x):
while x:
yield bin(x % 16)[2:].zfill(4)
x >>= 4
def nibble(x):
return "_".join(gen(x))
Try:
def bin_nibble(val):
b = bin(val)[2:]
new_b = '_'.join([b[::-1][i:i+4][::-1] for i in range(0, len(b), 4)][::-1])
If you want to add leading zeros:
def bin_nibble(val):
b = bin(val)[2:]
new_b = '_'.join([b[::-1][i:i+4][::-1] for i in range(0, len(b), 4)][::-1])
return ''.join(['0']*(4 - len(b) % 4 if len(b) % 4 != 0 else 0) + [new_b])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With