Created
November 12, 2025 16:15
-
-
Save optixx/22a33d1834acd3cab77509ac18757bc9 to your computer and use it in GitHub Desktop.
Display decimal, hex, binary of a value with two's complement support
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
| #!/usr/bin/env python3 | |
| import sys | |
| def parse_value(value_str): | |
| """Parse a value string as int (supports decimal and hex).""" | |
| try: | |
| if value_str.lower().startswith("0x"): | |
| return int(value_str, 16) | |
| else: | |
| return int(value_str, 10) | |
| except ValueError: | |
| print(f"Invalid input: {value_str}") | |
| sys.exit(1) | |
| def to_twos_complement(value, bits=32): | |
| """Convert signed int to its unsigned two's complement representation.""" | |
| if value < 0: | |
| value = (1 << bits) + value | |
| return value & ((1 << bits) - 1) | |
| def format_hex_grouped(value, bits=32): | |
| """Format as hex, grouped per byte.""" | |
| hex_str = f"{value:0{bits // 4}X}" | |
| # Group in bytes (2 hex chars per group) | |
| return " ".join(hex_str[i:i+2] for i in range(0, len(hex_str), 2)) | |
| def format_bin_grouped(value, bits=32): | |
| """Format as binary, grouped per byte (8 bits per group).""" | |
| bin_str = f"{value:0{bits}b}" | |
| return " ".join(bin_str[i:i+8] for i in range(0, bits, 8)) | |
| def main(): | |
| if len(sys.argv) != 2: | |
| print("Usage: numinfo.py <value>") | |
| print("Example: numinfo.py 0xFF or numinfo.py -42") | |
| sys.exit(1) | |
| input_str = sys.argv[1] | |
| bits = 32 | |
| val = parse_value(input_str) | |
| # Convert to unsigned if negative | |
| unsigned_val = to_twos_complement(val, bits) | |
| # Signed interpretation (two's complement) | |
| signed_val = val if val < (1 << (bits - 1)) else val - (1 << bits) | |
| print(f"Input: {input_str}") | |
| print(f"Decimal (signed): {signed_val}") | |
| print(f"Decimal (unsigned): {unsigned_val}") | |
| print(f"Hex: {format_hex_grouped(unsigned_val)}") | |
| print(f"Binary: {format_bin_grouped(unsigned_val)}") | |
| if __name__ == "__main__": | |
| main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment