Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert string of 0 and 1 to it's binary equivalent python [duplicate]

Tags:

python

binary

I have a string of 6 characters (only 0s and 1s)on which I have to use binary operations. I came across a few pages but most mentioned converting characters to binary and appending them to give the final result.

I have to use it in this function

def acmTeam(topic):
    global finalCount
    for i in range(len(topic)-1):
        for j in range(i+1,len(topic)):
            final=toBinary(topic[i])|toBinary(topic[j])
            print(final)

One example value of topic is

['10101', '11100', '11010', '00101']

and i want 10101 and 11100 binary values

Here I can create my own function toBinary to convert it to binary equivalent and return, but is there any inbuilt function or more efficient way to do so in python?

Thanks in advance :)

like image 861
Rishabh Ryber Avatar asked Jan 26 '23 02:01

Rishabh Ryber


1 Answers

Try this:

int(s, base=2)

for example,

for i in ['10101', '11100', '11010', '00101']:
    print(int(i, base=2))

@metatoaster also mentioned this.

like image 77
Calder White Avatar answered Jan 28 '23 15:01

Calder White