当前位置:网站首页>HJ整数与IP地址间的转换
HJ整数与IP地址间的转换
2022-06-28 07:36:00 【有勇气的牛排】
描述
原理:ip地址的每段可以看成是一个0-255的整数,把每段拆分成一个二进制形式组合起来,然后把这个二进制数转变成
一个长整数。
举例:一个ip地址为10.0.3.193
| 每段数字 | 相对应的二进制数 |
|---|---|
| 10 | 00001010 |
| 0 | 00000000 |
| 3 | 00000011 |
| 193 | 11000001 |
组合起来即为:00001010 00000000 00000011 11000001,转换为10进制数就是:167773121,即该IP地址转换后的数字就是它了。
数据范围:保证输入的是合法的 IP 序列
输入描述:
输入
1 输入IP地址
2 输入10进制型的IP地址
输出描述:
输出
1 输出转换成10进制的IP地址
2 输出转换后的IP地址
示例1
输入:
10.0.3.193
167969729
输出:
167773121
10.3.3.193
牛客 Python
def ip2num(ip):
res = ''
for i in ip.split('.'):
res = res + bin(int(i))[2:].rjust(8, "0")
return int('0b' + res, 2)
def num2ip(num):
result = ''
bin_str = bin(int(num))[2:]
bin_str = bin_str.rjust(32, '0')
res = ''
for item in range(4):
res = res + "." + str(int('0b' + bin_str[item * 8:item * 8 + 8], 2))
return res[1:]
if __name__ == '__main__':
# while True:
try:
print(ip2num(input()))
print(num2ip(input()))
# print(ip2num("10.0.3.193"))
# print(num2ip("167969729"))
except:
pass
边栏推荐
猜你喜欢
![[thanos source code analysis series]thanos query component source code analysis](/img/e4/2a87ef0d5cee0cc1c1e1b91b6fd4af.png)
[thanos source code analysis series]thanos query component source code analysis

Recommended system series (Lecture 5): Optimization Practice of sorting model

Kubernetes cluster lossless upgrade practice

Leetcode learning records

SQL statement optimization steps (1)

Redis implements distributed locks

kubernetes部署thanos ruler的发送重复告警的一个隐秘的坑

kubernetes删除pod的流程的源码简析

HTTP Caching Protocol practice

MySQL installation steps - installing MySQL on Linux (3)
随机推荐
R language ggmap
7-2 芬兰木棋 结构体排序
Hash slot of rediscluster cluster cluster implementation principle
Investment transaction and settlement of the fund
Block transmission by golang gin framework
mysql57 zip文件安装
Jetpack - defects of livedata component and Countermeasures
Analyze 5 indicators of NFT project
XML serialization backward compatible
卸载重装最新版mysql数据库亲测有效
Using interceptor and cache to complete interface anti brushing operation
Install haproxy
Solving the longest palindrome substring by dynamic programming
XML序列化向后兼容
goland IDE和delve调试位于kubernetes集群中的go程序
Is it safe for flush to open an account online
8 figures | analyze Eureka's first synchronization registry
Sword finger offer II 091 Paint the house
Is it reliable to register and open an account for stock speculation? Is it safe?
LLVM 与 Clang