3

I would like to perform a bitwise OR on two string representations of binary numbers, but I can't figure out how to convert the strings into raw binary.

a = '010110'
b = '100000'

a | b

should yield: 110110

I then want to count the number of on bits.
This should return:
4

0

2 Answers 2

3

You can convert the strings to binary using the built-in int() function and passing 2 as the base:

a = int('010110', 2)
b = int('100000', 2)

then OR the two values and count the bits by converting to a string and counting the "1" characters:

print bin(a | b).count("1")
Sign up to request clarification or add additional context in comments.

Comments

1

You could write a custom class derived from str and override its magic method responsible for the binary OR operator |.

There are many ways to implement the OR. The probably easiest one was already described by @samgak in his answer, you can use int with specifying the base number as 2 and then use its | operator:

class bitstr(str)
    def __or__(self, other):
        return bin(int(self, 2) | int(other, 2))[2:]
        # need to slice because 'bin' prefixes the result string with "0b".

This is how you could use it:

a = '010110'
b = bitstr('100000')

print(bitstr(a) | b)
# Output: 110110

You see that you need a conversion to bitstr somewhere, but it does not matter at which point. Also, for all other operations except the | operator, our custom bitstr behaves exactly like a normal str string, so you could use that everywhere if you want.

See this code running on ideone.com

Comments

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.