gpt4 book ai didi

python - 尝试将邮政编码转换为二进制时找不到错误

转载 作者:太空宇宙 更新时间:2023-11-03 16:57:15 25 4
gpt4 key购买 nike

这是我的代码,我觉得这应该可以工作。我刚才添加了 zipcode = str(zipcode) 来看看它是否可以工作,但它没有,所以我可能会把它拿出来,让原始的邮政编码成为一个字符串。我需要它是一个字符串,因为我不希望二进制数字实际相加。当我在 python shell 中初始化该函数时,它什么也不返回

def digitConvert(zipcode):
zipcode = str(zipcode)
n = 0
binary = ""
while n < len(zipcode):
if zipcode[n] == 0:
binary = binary + "11000"
n = n + 1
elif zipcode[n] == 1:
binary = binary + "00011"
n = n + 1
elif zipcode[n] == 2:
binary = binary + "00101"
n = n + 1
elif zipcode[n] == 3:
binary = binary + "00110"
n = n + 1
elif zipcode[n] == 4:
binary = binary + "01001"
n = n + 1
elif zipcode[n] == 5:
binary = binary + "01010"
n = n + 1
elif zipcode[n] == 6:
binary = binary + "01100"
n = n + 1
elif zipcode[n] == 7:
binary = binary + "10001"
n = n + 1
elif zipcode[n] == 8:
binary = binary + "10010"
n = n + 1
elif zipcode[n] == 9:
binary = binary + "10100"
n = n + 1
return binary

感谢您的帮助!

最佳答案

如果我理解正确的话,邮政编码是一个整数。这是一个将整数转换为二进制的 python 小函数。默认是您想要 24 位二进制。

def int2bin(n, count=24):
"""returns the binary of integer n, using count number of digits"""
return "".join([str((n >> y) & 1) for y in range(count-1, -1, -1)])

例如,我的邮政编码是 60517,所以我会这样做:

>>> print int2bin(60517)  
000000001110110001100101

如果我只想要 16 个二进制位:

>>> print int2bin(60517, 16)
1110110001100101

关于python - 尝试将邮政编码转换为二进制时找不到错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35324162/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com