Last active
August 30, 2022 23:04
-
-
Save emilio1625/0d798526818e54d7787ab0c8496ee4ba to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
This makes the python interpreter to print integers as hexadecimal or binary | |
this is based in a stack overflow answer but i cant find the original source :c | |
""" | |
import sys, math | |
def nbits(a, pad=4): | |
""" | |
Number of bits needed to represent a integer including the padding desired | |
""" | |
n = math.ceil(math.log2(abs(a)+1)) | |
if n % pad: | |
n += (pad - (n % pad)) | |
return n | |
def group_bits(n, rep='x', digits_per_group=4, sep="_"): | |
""" | |
Creates a string representing a integer in bin or hex dividing the | |
digits in groups of the specified size and adding padding if needed | |
""" | |
if rep.lower() == 'x': # hex | |
bits_per_digit = 4 | |
else: # bin | |
bits_per_digit = 1 | |
bits_per_group = digits_per_group * bits_per_digit | |
num_bits = nbits(n, bits_per_group) | |
d = '{:0{}{}}'.format( | |
n & ((1<<num_bits)-1), # truncate negative numbers to a certain size | |
int(num_bits/bits_per_digit), # amount of leading zeros | |
rep | |
) | |
return sep.join(d[k:k+digits_per_group] for k in range(0, len(d), digits_per_group)) | |
def _out(o, rep='X', group_size=4): | |
if type(o).__name__ in ('int', 'long'): | |
print('0' + rep.lower() + group_bits(o, rep, digits_per_group=group_size)) | |
__builtins__._ = o | |
else: | |
sys.__displayhook__(o) | |
def hexon(size=4): | |
sys.displayhook = lambda x: _out(x, rep='X', group_size=size) | |
def hexoff(): | |
sys.displayhook=sys.__displayhook__ | |
def binon(size=4): | |
sys.displayhook = lambda x: _out(x, rep='b', group_size=size) | |
binoff = hexoff |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment