Skip to content Skip to sidebar Skip to footer

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

Solution 1:

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:

printbin(a | b).count("1")

Solution 2:

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:

classbitstr(str)
    def__or__(self, other):
        returnbin(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

Post a Comment for "Bitwise Operation On String Representation Of Binary Number Python 2.7"