Convert list items to binary

Suppose I have a list:

lst = [0, 1, 0, 0]

How can I get python to interpret this list as binary number 0100, so that 2*(0100)gives me 01000?

The only way I can think of is to first create a function that converts the "binary" elements to the corresponding integers (up to base 10), and then use the bin () function.

Is there a better way?

+4
source share
5 answers

You can use bitwise operators as follows:

>>> lst = [0, 1, 0, 0]
 >>> bin(int(''.join(map(str, lst)), 2) << 1)
'0b1000'
+4
source

The accepted answer connecting the string is not the fastest.

import random

lst = [int(i < 50) for i in random.choices(range(100), k=100)]


def join_chars(digits): 
    return int(''.join(str(i) for i in digits), 2)    

%timeit join_chars(lst) 
13.1 µs ± 450 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)


def sum_digits(digits): 
    return sum(c << i for i, c in enumerate(digits)) 

%timeit sum_digits(lst)                                                                                                                                                                                                 
5.99 µs ± 65.5 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

, sum_digits() 2!

+1

, .

lst = [0,1,1,0]

num = 0
for b in lst:
    num = 2 * num + b
print(num) # 6
0

:

x=[0, 1, 0, 0]
b=''.join(map(str,x))
print(b)

:

C:\python\prog>python trying.py

0100
0
source

You can try:

l = [0, 0, 1, 0]
num = int(''.join(str(x) for x in l), base=2)
-1
source

Source: https://habr.com/ru/post/1651169/


All Articles