Search code examples
pythonpython-2.7binarybit-manipulationbitwise-operators

Python bitwise operation on large binary strings


I want to perform bitwise operation on binary strings with length more than 100 zeros and ones. I know i can convert them using something like int('1'*100, 2) which prints 1267650600228229401496703205375L with L character at the end. Then use python bitwise operators but I think it's a bad idea to convert them into integer. Is there any other way to do this?


Solution

  • I'm guessing that you do not like the idea of using integers because it obfuscates your underlying data. Plus it makes it difficult to work with strings that start with '0' (because they trimmed off when converting to an integer), not to mention the subtleties of signed integers and endianness.

    Try using the bitarray module, can be installed with pip: pip install bitarray.

    from bitarray import bitarray
    ba1 = bitarray('0' + '1'*100)
    ba2 = bitarray('1' + '0'*100)
    
    len(ba1)  # 101
    len(ba2)  # 101
    ba1[0]    # False
    ba2[0]    # True
    
    ba1 | ba2  # bitarray('1111111111.......)
    
    # get your string back
    ba1.to01()  # "01111111......."
    

    I can't speak for the efficiency. But at least it feels clear as to what you are working with.

    Also works in python3

    Docs: https://pypi.python.org/pypi/bitarray/0.8.1