Skip to content

Instantly share code, notes, and snippets.

@IceCereal
Last active April 3, 2023 12:57
Show Gist options
  • Save IceCereal/4b4e2be59096e39db9b97cd80aec2412 to your computer and use it in GitHub Desktop.
Save IceCereal/4b4e2be59096e39db9b97cd80aec2412 to your computer and use it in GitHub Desktop.
A (better-than-before) command line utility program written in python3 to convert numbers between different bases
#!/usr/bin/env python3
from textwrap import wrap
from argparse import ArgumentParser
if __name__ == "__main__":
space_bin = 8
space_oct = 3
space_hex = 4
parser = ArgumentParser(
prog="typeconvert",
description="A supertiny utility program written in python3 to convert "
"numbers between different bases",
epilog="-- IceCereal --")
parser.add_argument("--bin", type=str, help="number in binary")
parser.add_argument("--oct", type=str, help="number in octal")
parser.add_argument("--dec", type=int, help="number in decimal")
parser.add_argument("--hex", type=str, help="number in hexadecimal")
parser.add_argument("--no-space", action='store_true', help="disable spaces"
" in output")
args = parser.parse_args()
numbers = []
if args.bin:
numbers.append(int(args.bin, 2))
if args.oct:
numbers.append(int(args.oct, 8))
if args.dec:
numbers.append(args.dec)
if args.hex:
numbers.append(int(args.hex, 16))
if args.no_space:
space_bin = 64
space_oct = 22
space_hex = 16
print("==================")
for number in numbers:
print("bin:", " ".join(wrap(format(number, '064b'), space_bin)))
print("oct:", " ".join(wrap(format(number, '022o'), space_oct)))
print("dec: %d" % number)
print("hex: 0x" + " ".join(wrap(format(number, '016X'), space_hex)))
print("==================")

Typeconvert_V2

  • Download the typeconvert gist.

  • Make it an executable - chmod 755 typeconvert

  • Move it into your path - ~/.local/bin/, /usr/local/bin/

  • You might have to close your terminal and open it again in order to use it


usage: typeconvert [-h] [--bin BIN] [--oct OCT] [--dec DEC] [--hex HEX] [--no-space]

A supertiny utility program written in python3 to convert numbers between different bases

options: -h, --help show this help message and exit --bin BIN number in binary --oct OCT number in octal --dec DEC number in decimal --hex HEX number in hexadecimal --no-space disable spaces in output


examples: ./typeconvert --bin 111 --oct 1231 --dec 10 --hex 0xF23

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment