我有这个代码将二进制转换为十六进制
## The Input part
l = raw_input('Input 8-bit number: ')
j = list(l)
## Value Error part
t = [int(x) for x in j]
if len(t) != 8 or len([n for n in t if n not in (1, 0)]) != 0:
raise ValueError('NOT 1 OR 0, or NOT CORRECT LENGTH')
## The Conversion part
a = l[0]
b = l[1]
c = l[2]
d = l[3]
e = l[4]
f = l[5]
g = l[6]
h = l[7]
p = a+b+c+d
q = e+f+g+h
y = hex(int(p, 2))[2:]
z = hex(int(q, 2))[2:]
## The Results part
print
print 'Results'
print 'Binary: ',l
print 'Hex: ',y+z
我的整个转换部分非常长,因为无论何时我尝试转换前面有0000的数字它都不会打印0而我需要它来打印0是否有办法在不进行长时间处理的情况下执行此操作
答案 0 :(得分:2)
如果我理解正确,您希望打印出从二进制输入l
获得的2位十六进制数字。你可以这样做:
print 'Hex: ', hex(int(l, 2))[2:].zfill(2)
答案 1 :(得分:1)
略过所有编码。
首先,请尝试hex()
:http://docs.python.org/library/functions.html#hex
然后,查看format()
:http://docs.python.org/library/functions.html#format
答案 2 :(得分:0)
print "%02x" % int(raw_input("Enter a number in binary: "), 2)