python hex 补0_Python保留前导零的二进制到十六进制转换
我想把一個576位的二進制數轉換成hex,所以我編寫了下面的python腳本。雖然寫作很有趣,但我相信它是巨大的,丑陋的,而且很可能是不必要的復雜。我想知道是否有新的更有效的方法來使用一些內置的python。我使用任何我能找到的方法的問題是保留前導零,因為這是絕對關鍵的。下面是我用來測試的輸入和輸出以及我編寫的代碼。在
輸入:000011110111101011000101
輸出:
^{pr2}$
代碼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 hex 补0_Python保留前导零的二进制到十六进制转换的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 回溯法基本思想_数据结构之简单的回溯算法
- 下一篇: python queue模块安装_Pyt