【发布时间】:2015-03-09 19:53:10
【问题描述】:
我想将 576 位二进制数转换为十六进制,所以我编写了以下 python 脚本。虽然写起来很有趣,但我认为它庞大、丑陋,而且很可能是不必要的复杂。我想知道是否有人使用内置的一些 python 来使用更有效的方法来做到这一点。我使用任何我能找到的问题是保留前导零,因为它是绝对关键的。下面是我用来测试的输入输出和我写的代码。
输入:
000011110111101011000101
输出:
0f7ac5
代码
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)
【问题讨论】:
标签: python binary type-conversion hex