0

ユーザーが入力した IPv4 アドレスをバイナリおよびベース 10 アドレスに変換するプログラムが必要です。このようなもの:

input: 142.55.33.1
output (base 10): [2385977601]
output (base 2): [10001110 00110111 00100001 00000001]

これまでのところ、それをbase10アドレスに変換することはできましたが、base 2の問題を回避できないようです:

#!/usr/bin/python3

ip_address = input("Please enter a dot decimal IP Address: ")

#splits the user entered IP address on the dot
ListA = ip_address.split(".")
ListA = list(map(int, ListA))

ListA = ListA[0]*(256**3) + ListA[1]*(256**2) + ListA[2]*(256**1) + ListA[3]
print("The IP Address in base 10 is: " , ListA)

#attempt at binary conversion (failing)
#ListA = ListA[0]*(2**3) + ListA[1]*(2**2) + ListA[2]*(2**1) + ListA[3]
#print("The IP Address in base 2 is: " , ListA)

どんな助けでも大歓迎です。ありがとうございました。

4

2 に答える 2

4

使用format:

>>> text = '142.55.33.1'
>>> ' ' .join(format(int(x), '08b') for x in text.split('.'))
'10001110 00110111 00100001 00000001'

リストが必要な場合:

>>> [format(int(x), '08b') for x in text.split('.')]
['10001110', '00110111', '00100001', '00000001']

ここで format は整数をバイナリ文字列表現に変換します:

>>> format(8, 'b')
'1000'
>>> format(8, '08b')  #with padding
'00001000'
于 2013-11-02T16:43:56.343 に答える
1

使用str.format:

>>> ip_address = '142.55.33.1'
>>> ['{:08b}'.format(int(n)) for n in ip_address.split('.')]
['10001110', '00110111', '00100001', '00000001']
>>> ' '.join('{:08b}'.format(int(n)) for n in ip_address.split('.'))
'10001110 00110111 00100001 00000001'
于 2013-11-02T16:43:04.190 に答える