1

If I have two strings of binary representation. How to do bitwise on them?

Example

a = '101'
b = '010'
c = a | b
c => '111'
4

2 Answers 2

3

First, use int to convert the binary strings to numbers. You can use the second parameter of int to specify the base, 2 in this case. Then, you can use | to "or" the numbers and bin or a format-string (many different possibilities here) to convert back to binary.

>>> a = '101'
>>> b = '010'
>>> c = int(a, 2) | int(b, 2)
>>> bin(c)
'0b111'
>>> f"{c:b}"
'111'
>>> format(c, "b")
'111'

The latter two can also be used to add any number of leading zeros, if necessary, e.g. using 08b instead of b in the format string.

Sign up to request clarification or add additional context in comments.

2 Comments

@AnirbanNag'tintinmj' Then you are using an older version of Python. Use the ones that do not give an error.
Removes leading zeros, though, for example '010' and '001' turn into '11' instead of '011'.
1

A solution that works on the strings (not via ints) and keeps leading zeros intact:

>>> a = '0101'
>>> b = '0011'
>>> ''.join(map(max, a, b))
'0111'

Needs the strings to have equal length, but given your example where one string has a leading zero so it's as long as the other, I guess that's the case for you.

2 Comments

Neat... but you might add a note that both strings have to be the same length.
Hmm, since the OP's example is '101' and '010', not '10', I believe their strings do have the same length.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.