Python IP 到整数的转换未按预期工作
Python IP to integer conversion not working as expected
我正在使用 here 提供的答案将字符串 IP 转换为整数。但我没有得到预期的输出。具体方法是
>>> ipstr = '1.2.3.4'
>>> parts = ipstr.split('.')
>>> (int(parts[0]) << 24) + (int(parts[1]) << 16) + \
(int(parts[2]) << 8) + int(parts[3])
但是当我提供值 172.31.22.98
时,我得到 2887718498
回来。但是,我希望看到 Google 的 Guava 库 https://google.github.io/guava/releases/20.0/api/docs/com/google/common/net/InetAddresses.html#fromInteger-int-
提供的值 -1407248798
此外,我已经验证 this 服务提供了预期的输出,但上述 Whosebug 答案提供的所有答案 return 2887718498
请注意,我不能使用任何第三方库。所以我几乎只能使用手写代码(没有导入)
更好的方法是使用库方法
>>> from socket import inet_aton
>>> int.from_bytes(inet_aton('172.31.22.98'), byteorder="big")
2887718498
这与上面的结果相同
这是一种将其视为有符号整数的方法
>>> from ctypes import c_long
>>> c_long(2887718498)
c_long(-1407248798)
不用导入就可以做到(但是为什么呢?以上都是第一方CPython)
>>> x = 2887718498
>>> if x >= (1<<31): x-= (1<<32)
>>> x
-1407248798
在尝试执行与 OP 相同的操作时发现此 post。开发以下内容是为了让我简单的头脑理解并让某人从中受益。
baseIP = '192.168.1.0'
baseIPFirstOctet = (int((baseIP).split('.')[0]))
baseIPSecondOctet = (int((baseIP).split('.')[1]))
baseIPThirdOctet = (int((baseIP).split('.')[2]))
baseIPFourthOctet = (int((baseIP).split('.')[3]))
我正在使用 here 提供的答案将字符串 IP 转换为整数。但我没有得到预期的输出。具体方法是
>>> ipstr = '1.2.3.4'
>>> parts = ipstr.split('.')
>>> (int(parts[0]) << 24) + (int(parts[1]) << 16) + \
(int(parts[2]) << 8) + int(parts[3])
但是当我提供值 172.31.22.98
时,我得到 2887718498
回来。但是,我希望看到 Google 的 Guava 库 https://google.github.io/guava/releases/20.0/api/docs/com/google/common/net/InetAddresses.html#fromInteger-int-
-1407248798
此外,我已经验证 this 服务提供了预期的输出,但上述 Whosebug 答案提供的所有答案 return 2887718498
请注意,我不能使用任何第三方库。所以我几乎只能使用手写代码(没有导入)
更好的方法是使用库方法
>>> from socket import inet_aton
>>> int.from_bytes(inet_aton('172.31.22.98'), byteorder="big")
2887718498
这与上面的结果相同
这是一种将其视为有符号整数的方法
>>> from ctypes import c_long
>>> c_long(2887718498)
c_long(-1407248798)
不用导入就可以做到(但是为什么呢?以上都是第一方CPython)
>>> x = 2887718498
>>> if x >= (1<<31): x-= (1<<32)
>>> x
-1407248798
在尝试执行与 OP 相同的操作时发现此 post。开发以下内容是为了让我简单的头脑理解并让某人从中受益。
baseIP = '192.168.1.0'
baseIPFirstOctet = (int((baseIP).split('.')[0]))
baseIPSecondOctet = (int((baseIP).split('.')[1]))
baseIPThirdOctet = (int((baseIP).split('.')[2]))
baseIPFourthOctet = (int((baseIP).split('.')[3]))