I am working on an IPV4 breakdown where I have the necessary values in a string variable to represent the binary
(example: 00000000.00000000.00001111.11111111
) This is a string
I need a way to turn this string into binary to then properly convert it to it's proper integer value
(in this case 0.0.15.255
)
I've seen posts asking about something similar but attempting to apply it to what I'm working on has been unsuccessful
Apologies if this made no sense this is my first time posing a question here
First split the string on .
then convert each to integer equivalent of the binary representation using int
builtin passing base=2
, then convert to string, finally join them all on .
>>> text = '00000000.00000000.00001111.11111111'
>>> '.'.join(str(int(i, base=2)) for i in text.split('.'))
# output
'0.0.15.255'
You should split the data, convert and combine.
data = "00000000.00000000.00001111.11111111"
data_int = ".".join([str(int(i, 2)) for i in data.split(".")])
print(data_int) # 0.0.15.255
You can achieve this using int()
with base
argument.
You can know more about
int(x,base)
- here
'.'
and store it in a list lst
lst
, convert the item (binary string) to decimal using int(item, base=2)
and then convert it into string type.lst
using .
s = '00000000.00000000.00001111.11111111'
lst = s.split('.')
lst = [str(int(i,2)) for i in lst]
print('.'.join(lst))
# Output
0.0.15.255
Welcome! Once you have a string like this
s = '00000000.00000000.00101111.11111111'
you may get your integers in one single line:
int_list = list(map(lambda n_str: int(n_str, 2), s.split('.')))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.