'Convert elements of a list into binary
Suppose I have a list:
lst = [0, 1, 0, 0]
How can I make python interpret this list as a binary number 0100 so that 2*(0100) gives me 01000?
The only way that I can think of is to first make a function that converts the "binary" elements to corresponding integers(to base 10) and then use bin() function..
Is there a better way?
Solution 1:[1]
The accepted answer, joining a 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)
So bit-banging sum_digits() comes first by a factor of x2!
Solution 2:[2]
This is not a fancy one-liner, but simple and fast.
lst = [0,1,1,0]
num = 0
for b in lst:
num = 2 * num + b
print(num) # 6
Solution 3:[3]
slightly different approach with comprehension (i hope it will be helpful for someone)
arr =[192, 168, 0, 1]
arr_s = [bin(i)[2:].zfill(8) for i in ar]
num = int(''.join(arr_s), 2)
same, but reverse order (and also one-liner suitable for lambdas )
arr = [24, 85, 0]
num = int(''.join( [bin(i)[2:].zfill(8) for i in arr[::-1]] ), 2)
using bit-wise and reduce:
reduce ((lambda x,y: (x<<8)|y), arr[::-1])
Solution 4:[4]
You can use this code for concatenating the list elements:
x=[0, 1, 0, 0]
b=''.join(map(str,x))
print(b)
Output:
C:\python\prog>python trying.py
0100
Solution 5:[5]
In Jupyter:-
lst = [4,5,7,1,2]
bin(int(''.join(map(str, lst)))<<1)
o/p:- '0b10110010100100000'
In Python Shell:-
>>> lst =[4,5,7,1,2]
>>> bin(int(''.join(map(str, lst)))<<1)
o/p:- '0b10110010100100000'
Solution 6:[6]
You can try:
l = [0, 0, 1, 0]
num = int(''.join(str(x) for x in l), base=2)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | ankostis |
| Solution 2 | VPfB |
| Solution 3 | |
| Solution 4 | double-beep |
| Solution 5 | Cprk Praveen |
| Solution 6 | Victor Fernandez |
