Created
November 13, 2015 12:31
-
-
Save festlv/2147917fff54bc518c8a to your computer and use it in GitHub Desktop.
Small utility to look at number representation in different bases.
This file contains 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 | |
""" | |
Small utility to see number representation in different bases. Example usage: | |
$ ./bits.py | |
> 9023 | |
DEC: 9023, HEX: 233F, BIN: 0010 0011 0011 1111 | |
> 25407 | |
DEC: 25407, HEX: 633F, BIN: 0110 0011 0011 1111 | |
> q | |
$ | |
""" | |
import sys | |
import math | |
import os | |
import readline | |
histfile = os.path.join(os.path.expanduser("~"), ".bitshist") | |
try: | |
readline.read_history_file(histfile) | |
except IOError: | |
pass | |
import atexit | |
atexit.register(readline.write_history_file, histfile) | |
del os, histfile | |
class BitConverter: | |
def get_input(self): | |
return input("> ") | |
def _try_base(self, num, base): | |
try: | |
n = int(num, base) | |
except ValueError: | |
return False | |
return n | |
def _process_bin(self, num): | |
""" Returns 0000 0000 0000 """ | |
bin_string = bin(num)[2:] | |
num_octets = math.ceil(len(bin_string) / 8.0) | |
bin_string = bin_string.zfill(num_octets * 8) | |
ret_list = [] | |
for octet in range(0, num_octets): | |
l = [] | |
l.append(bin_string[octet * 8 : (octet + 1) * 8 - 4]) | |
l.append(bin_string[octet * 8 + 4 : (octet + 1) * 8]) | |
ret_list.append(" ".join(l)) | |
return " ".join(ret_list) | |
def process_number(self, num): | |
n = False | |
for base in (10, 16, 2, 8): | |
n = self._try_base(num, base) | |
if type(n) is int: | |
break | |
if type(n) is not int: | |
print("Could not process %s\n" % (num)) | |
return | |
print("DEC: %6d, HEX: %6s, BIN: %s" % (n, hex(n).upper()[2:], | |
self._process_bin(n))) | |
def process_input(self, inp): | |
if inp[0] == 'h': | |
print("Enter a number to see it in different representations.") | |
print("Supported formats: 0x01AB for hex, 123 for decimal, b001 for binary") | |
print("help, quit") | |
elif inp[0] == 'q': | |
sys.exit(0) | |
else: | |
# this should be a number | |
self.process_number(inp) | |
def loop(self): | |
while True: | |
i = self.get_input() | |
self.process_input(i) | |
if __name__ == "__main__": | |
c = BitConverter() | |
c.loop() | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment