程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

[computer test question (implementation language: python3)] conversion between integer and IP address

編輯:Python

Title Description
principle :ip Each segment of the address can be regarded as a 0-255 The integer of , Split each segment into a binary form and put it together , Then convert this binary number into
A long integer .
give an example : One ip The address is 10.0.3.193
Every number Corresponding binary number
10 00001010
0 00000000
3 00000011
193 11000001

The combination is :00001010 00000000 00000011 11000001, Convert to 10 The hexadecimal number is :167773121, That is, the IP The number after address conversion is it .

This question contains several groups of input use cases , Each set of use cases requires you to ip Address to integer 、 Convert an integer to ip Address .

Input description :
Input

1 Input IP Address
2 Input 10 Binary IP Address

Output description :
Output

1 Output to 10 It's binary IP Address
2 Output converted IP Address

Example 1
Input

10.0.3.193
167969729

Output

167773121
10.3.3.193

The code implementation is as follows :


def func():
while True:
try:
ip = list(map(int,input().split('.')))
n = int(input())
res = ''
for i in ip:
v = '{:b}'.format(i)
v = v.rjust(8,'0')
res +=v
res = int(res,2)
print(res)
v = '{:b}'.format(n)
v = v.rjust(32,'0')
res = []
for i in range(0,len(v)-7,8):
a = int(v[i:i+8],2)
res.append(str(a))
print('.'.join(res))
except Exception as e:
#print(e)
break
if __name__ == '__main__':
func()

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved