Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple way to print binary numbers in groups of nibbles

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?

like image 811
Tjaart Avatar asked Jun 07 '18 08:06

Tjaart


2 Answers

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))
like image 136
hilberts_drinking_problem Avatar answered Nov 15 '22 06:11

hilberts_drinking_problem


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])
like image 33
Neb Avatar answered Nov 15 '22 07:11

Neb