题解 | #整数与IP地址间的转换#
整数与IP地址间的转换
https://www.nowcoder.com/practice/66ca0e28f90c42a196afd78cc9c496ea
湖边嗯造!
originalIp = str(input()).split('.')
originalNum = int(input())
newIpBinStr = ""
tmpIpBinList = list()
for thisNumStr in originalIp:
thisNumInt = int(thisNumStr)
while thisNumInt != 0:
tmpIpBinList.append('1' if thisNumInt % 2 == 1 else '0')
thisNumInt //= 2
tmpIpBinList.reverse()
if len(tmpIpBinList) < 8:
tmpIpBinList = ['0'] * (8 - len(tmpIpBinList)) + tmpIpBinList
newIpBinStr += ''.join(_ for _ in tmpIpBinList)
tmpIpBinList.clear()
newIpBinList = [_ for _ in newIpBinStr]
newIpBinList.reverse()
newIpDecNum = 0
tmpBinTimes = 0
for i in range(len(newIpBinList)):
if newIpBinList[i] == '1':
newIpDecNum += 2 ** tmpBinTimes
tmpBinTimes += 1
newNumBinStr = ""
tmpNumBinList = list()
while originalNum != 0:
tmpNumBinList.append('1' if originalNum % 2 == 1 else '0')
originalNum //= 2
tmpNumBinList.reverse()
if len(tmpNumBinList) < 32:
tmpNumBinList = ['0'] * (32 - len(tmpNumBinList)) + tmpNumBinList
tmpNumBinList.reverse()
tmpNumBinList = [''] + tmpNumBinList
newDecIpStr = ""
tmpDecInt = 0
tmpBinTimes1 = 0
for i in range(1, len(tmpNumBinList) + 1):
if tmpNumBinList[i] == '1':
tmpDecInt += 2 ** tmpBinTimes1
tmpBinTimes1 += 1
if i % 8 == 0:
newDecIpStr = ('.' if i < len(tmpNumBinList) - 1 else '') + str(tmpDecInt) + newDecIpStr
tmpDecInt = 0
tmpBinTimes1 = 0
if i == len(tmpNumBinList) - 1:
break
print(newIpDecNum)
print(newDecIpStr)
查看6道真题和解析