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'
khelwood
59.8k14 gold badges91 silver badges116 bronze badges
asked Oct 20, 2020 at 14:10
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.

answered Oct 20, 2020 at 14:26
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.

answered Oct 20, 2020 at 16:54

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

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.