Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 575
humble Avatar asked Aug 13 '16 17:08

humble


People also ask

How do you convert list elements into sets?

We can convert the list into a set using the set() command, where we have to insert the list name between the parentheses that are needed to be converted. Hence, in the above case, we have to type the set(the_names) in order to convert the names, present in the list into a set.

How do you convert a list of elements into a single string?

To convert a list to a string, use Python List Comprehension and the join() function. The list comprehension will traverse the elements one by one, and the join() method will concatenate the list's elements into a new string and return it as output.

How do you change a list of elements into integers?

This basic method to convert a list of strings to a list of integers uses three steps: Create an empty list with ints = [] . Iterate over each string element using a for loop such as for element in list . Convert the string to an integer using int(element) and append it to the new integer list using the list.


1 Answers

You can use bitwise operators like this:

>>> lst = [0, 1, 0, 0]
 >>> bin(int(''.join(map(str, lst)), 2) << 1)
'0b1000'
like image 117
styvane Avatar answered Sep 20 '22 18:09

styvane