【发布时间】:2021-09-28 11:38:04
【问题描述】:
我正在编写一个函数来获取一个 IP 地址,将它的每个部分(由“。”分隔)转换为一个 8 位二进制数字。然后我想组合所有二进制数并得到一个大的 32 位数字,我想将其转换为十进制。我的 convert 函数在作为独立测试时可以正常工作,但是当它在循环中运行时,它会给我TypeError: 'str' object cannot be interpreted as an integer 错误。
这是问题:(从代码战 - IPv4 到 int32)
获取以下 IPv4 地址:128.32.10.1 该地址有 4 个八位字节,其中每个八位字节是一个字节(或 8 位)。
第一个八位字节 128 具有二进制表示:10000000 第二个八位组 32 具有二进制表示:00100000 第 3 个八位组 10 具有二进制表示:00001010 第 4 个八位字节 1 具有二进制表示:00000001 所以 128.32.10.1 == 10000000.00100000.00001010.00000001
因为上面的IP地址是32位的,我们可以用32位的数字来表示:2149583361。
编写一个函数 ip_to_int32(ip) (JS: ipToInt32(ip)),它接受一个 IPv4 地址并返回一个 32 位数字。
ip_to_int32("128.32.10.1") => 2149583361
def convert(x):
return int(bin(x).replace("0b", ''))
def ip_to_int32(ip):
data = ip.split('.')
converted = []
for i in range(len(data)):
converted.append(convert(data[i]))
str = ''
for i in converted:
str += i
num = int(str)
return dec(num).replace('0d', '')
这是我得到的错误:
Traceback (most recent call last):
File "tests.py", line 4, in <module>
test.expect(ip_to_int32("128.114.17.104") == 2154959208, "wrong integer for ip: 128.114.17.104")
File "/workspace/default/solution.py", line 8, in ip_to_int32
converted.append(convert(data[i]))
File "/workspace/default/solution.py", line 2, in convert
return int(bin(x).replace("0b", ''))
TypeError: 'str' object cannot be interpreted as an integer
这是测试文件:
test.describe("Basic Tests")
test.expect(ip_to_int32("128.114.17.104") == 2154959208, "wrong integer for ip: 128.114.17.104")
test.expect(ip_to_int32("0.0.0.0") == 0, "wrong integer for ip: 0.0.0.0")
test.expect(ip_to_int32("128.32.10.1") == 2149583361, "wrong integer for ip: 128.32.10.1")
感谢您的帮助!
【问题讨论】:
-
这里有很多东西。但具体的错误是您试图调用
bin('128'),因为字符串被拆分然后传递给convert。假设你的意思是bin(int('128'))。 -
嗨,非常感谢!所以 -
bin()函数将 int 作为输入?我不知道。生病尝试一下,让你知道。感谢您的帮助!
标签: python arrays function logic number-systems