1

Is there any built in function in Python to split a 32 bit binary number into 4 separate 8 bit binary numbers? I am trying to convert an binary IP address into dotted decimal form and am trying split the numbers up and seem to be at a loss.

example:

Turning this:10000000111111110000001100001111

into: 10000000 11111111 00000011 00001111

So that I can convert into decimal from there. Thanks!

edit: I have been able to split the string into four sections, but now I am trying to convert each of those binary string values into a decimal number. I there a way to define each of the new string sections so I can use the int function on them?

2 Answers2

0
list(map(lambda s: int(s, base=2), [x[k:k + 8] for k in range(0, 32, 8)]))
bubble
  • 1,634
  • 12
  • 17
0

To resolve the question to have your string split up into 4 components, I'd first use a list comprehension with some string splicing. binary_string = "10000000111111110000001100001111"

data = [binary_string[:8], binary_string[8:16], binary_string[16:24], binary_string[24:32]]

A more concise way of writing this would be to use a list comprehension and increment by 8 over the string.:

data = [binary_string[i:i+8] for i in range(0,32,8)]

To answer your second question of converting it into numbers, you could just cast it using the int function.

data = [int(num) for num in data]

One note is that this may be a one-way function, since if your numbers start with 0's they'll be removed. So to convert them back into strings of length 8, you could use the zfill function:

data = [str(num).zfill(8) for num in data]
mattsap
  • 3,790
  • 1
  • 15
  • 36