Convert binary string to list of integers using Python

I am new to Python. Here is what I am trying to do:

  • Cut a long binary string into 3x fragments.
  • Store each "piece" in a list called a string.
  • Convert each binary fragment to a number (0-7).
  • Save the converted list of numbers to a new list called numbers.

Here is what I still have:

def traverse(R):
        x = 0
        while x < (len(R) - 3):
            row = R[x] + R[x+1] + R[x+2]
            ???

Thank you for your help! This is very valuable.

+5
source share
5 answers

Something like this should do this:

s = "110101001"
numbers = [int(s[i:i+3], 2) for i in range(0, len(s), 3)]
print numbers

Output:

[6, 5, 1]

Interrupting this step by step, first:

>>> range(0, len(s), 3)
[0, 3, 6]

The function range()returns a list of integers from 0, less than max len(s), to step 3.

>>> [s[i:i+3] for i in range(0, len(s), 3)]
["110", "101", "001"]

, s[i:i+3] i . s[i:i+3] , . :

>>> [int(s[i:i+3], 2) for i in range(0, len(s), 3)]
[6, 5, 1]

int(..., 2) ( 2, ) .

, , , 3 .

+11

, " " (.. ), "0" "1".

, 1 2,

row = [thestring[i:i+3] for i in xrange(0, len(thestring), 3)]

, 1 2 , len(thestring) 3, ; -).

3 4 temp :

aux = {}
for x in range(8):
  s = format(x, 'b')
  aux[s] = x
  aux[('00'+s)[-3:]] = x

3 4 :

numbers = [aux[x] for x in row]

dict , .

: , aux x. , s 1 3 , : s ( , row 3...), 3 0 s.

('00'+s)[-3:] "" "0 3", 3 ( [-3:]), of s ( '00'+s). s 3 , s, aux , , , ( if len(s)<3: , ; -).

(, x, ), ( 8 " ", ;-), .

... , . ...?

, row '01' : THAT- , aux, aux ( 1 001 , ;-). s, '1' , '001', - , oops, -).

, ...:

aux = {}
for x in range(8):
  s = format(x, 'b')
  aux[s] = x
  while len(s) < 3:
    s = '0' + s
    aux[s] = x

... , , , , ; -).

+7

, bitstring:

>>> import bitstring
>>> bits = bitstring.Bits('0b110101001')
>>> [b.uint for b in bits.cut(3)]
[6, 5, 1]

:

Python, , .

, , , , , . .

, , , , .. . O , , , .

, , 400 .

+1

! ! , , , gen-exps, list-comps, ..:

row = list (thestring [i: + 3] xrange (0, len (thestring), 3))

numbers = list (aux [x] x )

gen-exp .

0

:

( , 29)

.

a = ''

b = []

I stole this from a really good example in this forum, it formats the integer 29 by 5 bits, a bit from zero to four, and puts the bit string in the string variable "a". [edit] You must change the format from 0: 5b to 0: 05b to fill in zeros when the integer is <7.

a = '{0: 05b}'. format (29)

Look at your string variable

a

'11101'

divide the string into an array

b [0: 3] = a [0: 3]

this is exactly what i wanted.

b

['1', '1', '1']

0
source

All Articles