2

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

ThePyGuy
  • 17,779
  • 5
  • 18
  • 45
Matteo
  • 39
  • 4

4 Answers4

1

You can achieve this using int() with base argument.

You can know more about int(x,base) - here

  • Split the string at '.' and store it in a list lst
  • For every item in lst, convert the item (binary string) to decimal using int(item, base=2) and then convert it into string type.
  • Join the contents of 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
Ram
  • 4,724
  • 2
  • 14
  • 22
0

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'
ThePyGuy
  • 17,779
  • 5
  • 18
  • 45
0

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
Prudhvi
  • 1,095
  • 1
  • 7
  • 18
0

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('.')))