user803592
user803592

Reputation: 51

bitwise operation on string representation of binary number python 2.7

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

Upvotes: 3

Views: 2304

Answers (2)

Byte Commander
Byte Commander

Reputation: 6736

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

Upvotes: 1

samgak
samgak

Reputation: 24417

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")

Upvotes: 3

Related Questions