Numeral Systems

Decimal, Binary and Hexadecimal


    def pretty_print_numbers(i):
        print('int: {0:>14d}'.format(i))
        my_bin = '{0:b}'.format(i)
        if len(my_bin) < 5:
            print('bin: {:>14}'.format(my_bin))
        elif len(my_bin) == 5:
            print('bin: {:>9} {:>4}'.format(my_bin[0:1],my_bin[1:]))
        elif len(my_bin) == 6:
            print('bin: {:>9} {:>4}'.format(my_bin[0:2], my_bin[2:]))
        elif len(my_bin) == 7:
            print('bin: {:>9} {:>4}'.format(my_bin[0:3], my_bin[3:]))
        elif len(my_bin) == 8:
            print('bin: {:>9} {:>4}'.format(my_bin[0:4],my_bin[4:]))
        elif len(my_bin) == 9:
            print('bin: {:>4} {:>4} {:>4}'.format(my_bin[0], my_bin[1:5], my_bin[5:]))
        my_hex = '{0:x}'.format(i)
        if len(my_hex) == 1:
            print('hex: {:>14}'.format(my_hex))
        if len(my_hex) == 2:
            print('hex: {:>9} {:>4}'.format(my_hex[0], my_hex[1]))
        if len(my_hex) == 3:
            print('hex: {:>4} {:>4} {:>4}'.format(my_hex[0], my_hex[1], my_hex[2]))
        print('\n')

    for i in [1,15,16,255,256]:
        pretty_print_numbers(i)

    pretty_print_numbers(64)

    """
    int:              1
    bin:              1
    hex:              1


    int:             15
    bin:           1111
    hex:              f


    int:             16
    bin:         1 0000
    hex:         1    0


    int:            255
    bin:      1111 1111
    hex:         f    f


    int:            256
    bin:    1 0000 0000
    hex:    1    0    0


    int:             64
    bin:       100 0000
    hex:         4    0
    """

Binary and Octal


    def chunks(l, n):
        n = max(1, n)
        return list((l[i:i+n] for i in range(0, len(l), n)))


    def pretty_print_binocts(o_bin=0b111111):
        o_oct_str = oct(o_bin)[2:]
        o_oct_str_chunks = chunks(o_oct_str, 1)
        o_bin_str = bin(o_bin)[2:]
        o_bin_str_chunks = chunks(o_bin_str, 3)
        number = int(len(o_bin_str) / 3)
        blocks = ['{:>3}' for i in range(1, number + 1)]
        formatting_blocks = ' '.join(blocks)
        bin_formatting_string = 'bin: ' + formatting_blocks
        oct_formatting_string = 'oct: ' + formatting_blocks
        print(bin_formatting_string.format(*o_bin_str_chunks) + ' - ' + o_bin_str)
        print(oct_formatting_string.format(*o_oct_str_chunks) + ' - ' + o_oct_str)
        print('---')

    for o_bin in [0b111, 0b111111, 0b111111111, 0b101101101101]:
        pretty_print_binocts(o_bin)

    """
    bin: 111 - 111
    oct:   7 - 7
    ---
    bin: 111 111 - 111111
    oct:   7   7 - 77
    ---
    bin: 111 111 111 - 111111111
    oct:   7   7   7 - 777
    ---
    bin: 101 101 101 101 - 101101101101
    oct:   5   5   5   5 - 5555
    ---
    """