Files

67 lines
2.5 KiB
Python
Executable File

#!/usr/bin/env python3
# baseconv - convert numbers between bases (2/8/10/16/36)
# Usage: baseconv NUMBER --from BASE --to BASE | baseconv NUMBER [TO-BASE]
# Bases 2-36. Prefixes 0x, 0b, 0o auto-detect the input base when --from is omitted.
# Example: baseconv ff --from 16 --to 2 | baseconv 255 16 | baseconv 0b1010
import argparse, re, sys
DIGITS = "0123456789abcdefghijklmnopqrstuvwxyz"
def parse_num(s, base):
s = s.strip().lower()
neg = s.startswith("-")
s = s.lstrip("+-")
if base is None:
for prefix, b in (("0x", 16), ("0b", 2), ("0o", 8)):
if s.startswith(prefix):
return int(s, b) * (-1 if neg else 1)
base = 10
return int(s, base) * (-1 if neg else 1)
def to_base(n, base):
if n == 0:
return "0"
neg = n < 0
n = abs(n)
out = []
while n:
n, r = divmod(n, base)
out.append(DIGITS[r])
return ("-" if neg else "") + "".join(reversed(out))
def selftest():
assert parse_num("ff", 16) == 255
assert to_base(255, 16) == "ff" and to_base(255, 2) == "11111111"
assert to_base(parse_num("0b1010", None), 10) == "10"
assert to_base(parse_num("z", 36), 10) == "35"
assert to_base(parse_num("100", 2), 36) == "4"
assert to_base(-255, 16) == "-ff"
print("baseconv selftest: ok (hex/bin/base36, prefixes, negatives)")
return 0
def main():
p = argparse.ArgumentParser(prog="baseconv",
description="Convert numbers between bases 2-36 (0x/0b/0o prefixes auto-detected).")
p.add_argument("number", nargs="?", help="number to convert")
p.add_argument("to_base_arg", nargs="?", type=int, help="target base (shorthand for --to)")
p.add_argument("--from", dest="from_base", type=int, help="input base (2-36)")
p.add_argument("--to", dest="to_base", type=int, help="output base (2-36)")
p.add_argument("--selftest", action="store_true", help="run built-in checks and exit")
a = p.parse_args()
if a.selftest:
return selftest()
if not a.number:
p.error("NUMBER is required")
to_b = a.to_base or a.to_base_arg or 10
if not 2 <= to_b <= 36 or (a.from_base is not None and not 2 <= a.from_base <= 36):
print("baseconv: bases must be 2-36", file=sys.stderr); return 2
try:
n = parse_num(a.number, a.from_base)
except ValueError as e:
print(f"baseconv: bad number: {e}", file=sys.stderr); return 2
print(to_base(n, to_b))
return 0
if __name__ == "__main__":
sys.exit(main())