Skip to content

Instantly share code, notes, and snippets.

@kcxt
Last active January 16, 2025 14:45
Show Gist options
  • Save kcxt/3efe5c1515366c988d9c98ce6173b277 to your computer and use it in GitHub Desktop.
Save kcxt/3efe5c1515366c988d9c98ce6173b277 to your computer and use it in GitHub Desktop.
Pretty print values in binary

regbits

Small utility for pretty-printing numbers in binary, useful to manually decoding register without counting digits by hand.

Demo

; regbits 768


Value: 0x00000300 // 768

	 15  14  13  12  11  10   9   8   7   6   5   4   3   2   1   0
	╭───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───╮
	│   │   │   │   │   │   │ x │ x │   │   │   │   │   │   │   │   │
	╰───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───╯
#!/usr/bin/python3
import sys
cyan = "\x1b[36m"
green = "\x1b[32m"
blue = "\x1b[34m"
magenta = "\x1b[35m"
yellow = "\x1b[33m"
red = "\x1b[31m"
reset = "\x1b[0m"
def auto_int(x):
return int(x, 0)
value = int(sys.argv[1], 0)
print()
pretty_val = ""
if (value >> 32) > 0:
pretty_val += f"{cyan}{value >> 32:#10x}"
pretty_val += f"{green}{value & 0xFFFFFFFF:08x}{reset}"
else:
pretty_val += f"{green}{value & 0xFFFFFFFF:#010x}{reset}"
print(f"Value: {pretty_val} // {blue}{value}{reset}\n\n\t", end="")
bl = value.bit_length()
bits = int(bl/8 + 1) * 8
cols = [blue, cyan, green, magenta, yellow, red]
coli = len(cols)-1
for i in reversed(range(bits)):
if i % 8 == 7:
print(f"{cols[coli % len(cols)]}", end="")
coli -= 1
if coli < 0:
coli = len(cols)-1
print(f"{i:3d} ", end="")
print(f"{reset}\n", end="")
print("\t╭", end="")
print("───┬" * (bits - 1) , end="")
print("───╮\n\t│", end="")
for i in reversed(range(bits)):
print(" x │" if value & (1 << i) else " │", end="")
print("\n\t╰", end="")
print("───┴" * (bits - 1) , end="")
print("───╯\n")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment