我编写了一个代码来尝试将4位二进制数转换为十六进制数。唯一的问题是,当我输入一个以'1'开头的值时,它会产生转换,而如果我输入一个以'0'开头的值,它就不起作用。有什么帮助吗?
print ("""Here's how the program will work. You need to get your binary number ready.
if it is 8 bit, split it into four, because thats how hexadecimal works. Make sure all your conversions
are slip into '4' bits like this:
01001101 will turn into:
0100 ,and then 1101""")
time.sleep(6)
print ("""So, for example, the program will ask you for your binary number. Like this:
Enter your binary number here:
Then you put in your number, like this:
Enter your binary number here: 0100
Lastly, the program will give you your hexadecimal number, then ask you if you would
like to do another conversion in this area, or end program.""")
time.sleep(6)
HEXADECIMAL = int(input("Please enter your binary number here: "))
if HEXADECIMAL == 0000:
print ("Your hexadecimal value is 0")
if HEXADECIMAL == 0001:
print ("Your hexadecimal value is 1")
if HEXADECIMAL == 0010:
print ("Your hexadecimal value is 2")
if HEXADECIMAL == 0011:
print ("Your hexadecimal value is 3")
if HEXADECIMAL == 0100:
print ("Your hexadecimal value is 4")
if HEXADECIMAL == 0101:
print ("Your hexadecimal value is 5")
if HEXADECIMAL == 0110:
print ("Your hexadecimal value is 6")
if HEXADECIMAL == 0111:
print ("Your hexadecimal value is 7")
if HEXADECIMAL == 1000:
print ("Your hexadecimal value is 8")
if HEXADECIMAL == 1001:
print ("Your hexadecimal value is 9")
if HEXADECIMAL == 1010:
print ("Your hexadecimal value is A")
if HEXADECIMAL == 1011:
print ("Your hexadecimal value is B")
if HEXADECIMAL == 1100:
print ("Your hexadecimal value is C")
if HEXADECIMAL == 1101:
print ("Your hexadecimal value is D")
if HEXADECIMAL == 1110:
print ("Your hexadecimal value is E")
if HEXADECIMAL == 1111:
print ("Your hexadecimal value is F")
您可以尝试运行此代码并从例如0110开始,但它不会转换。有什么帮助吗?
答案 0 :(得分:0)
当你输入一个以前导0开头的整数时,python将它解释为在base 8中:
a = 0110
print a
将输出
72
因此,请在输入中删除前导0,或者在投射int()
之前删除它们
答案 1 :(得分:0)
您不必使用if/else
语句加时。有一种很酷的方式可以在python中使用int()
,如果使用字符串,int()
函数可以直接将它转换为任何基础。
HEXADECIMAL = str(input())
base = 16 # for Hex and 2 for binary
msg = "Your hexadecimal value is"
print (msg, int(HEXADECIMAL, base))
这将为你做到。但是如果你想坚持使用你的方法,你应该在二进制文件之前添加0b
0b0010
并执行操作,前导零是非法的,0010
是非法的。
答案 2 :(得分:-1)
替换,
HEXADECIMAL = int(input("Please enter your binary number here: "))
用,
temp = input("Please enter your binary number here: ")
HEXADECIMAL = int (temp)
如果出现错误,请删除睡眠时间。