I was wanting to convert a 576 bit binary number to hex so I wrote the following python script. While writing it was fun, i believe it to be massive, ugly, and most likely unnecessarily complicated. I was wondering if anyone new of a more efficient way to do this using some of the python built in. The issue I had using any that I could find was preserving the leading zeroes as it is absolutely critical. Below is the input and output i used to test and the code I wrote.
The input:
000011110111101011000101 The output:
0f7ac5 Code
file = open("binforhex.txt",'r') stream = file.read() num = [] byte = [] hexOut = [] n = 0 print stream for x in stream: num.append(x) while n < len(num): byte.append(int(num[n])) if n > 1: if (n + 1) % 4 == 0: if cmp([0, 0, 0, 0],byte) == 0 : hexOut.append('0') elif cmp([0, 0, 0, 1],byte) == 0 : hexOut.append('1') elif cmp([0, 0, 1, 0],byte) == 0 : hexOut.append('2') elif cmp([0, 0, 1, 1],byte) == 0 : hexOut.append('3') elif cmp([0, 1, 0, 0],byte) == 0: hexOut.append('4') elif cmp([0, 1, 0, 1],byte) == 0: hexOut.append('5') elif cmp([0, 1, 1, 0],byte) == 0: hexOut.append('6') elif cmp([0, 1, 1, 1],byte) == 0: hexOut.append('7') elif cmp([1, 0, 0, 0],byte) == 0: hexOut.append('8') elif cmp([1, 0, 0, 1],byte) == 0: hexOut.append('9') elif cmp([1, 0, 1, 0],byte) == 0: hexOut.append('a') elif cmp([1, 0, 1, 1],byte) == 0: hexOut.append('b') elif cmp([1, 1, 0, 0],byte) == 0: hexOut.append('c') elif cmp([1, 1, 0, 1],byte) == 0: hexOut.append('d') elif cmp([1, 1, 1, 0],byte) == 0: hexOut.append('e') elif cmp([1, 1, 1, 1],byte) == 0 : hexOut.append('f') byte.pop() byte.pop() byte.pop() byte.pop() n += 1 print ''.join(hexOut)