Search code examples
pythonpython-3.xbit-manipulationbitwise-operators

Bitwise operations on strings Python3.7


I have a large string of hex numbers, on which I want to perform some bitwise operations. I am trying to extract different bytes from it and then to apply bitwise OR, AND, XOR operations. Unfortunately, I don't know an easy way to do that, so every time I want to perform bitwise operations I am converting the hex into an integer. This is a simplified code.

data = "0x4700ff1de05ca7686c2b43f5e37e6dafd388761c36900ab37"

hex_data = "0x" + data[20:32]
four_bytes = hex_data[:10]
fifth_byte = "0x" + hex_data[10:12]
lshift_fourb = hex(int(four_bytes, 16) << 1)
bitwise_or_res = hex(int(lshift_fourb, 16) | int(fifth_byte, 16))

Is there an easy way to omit the constant conversion to integer and hex back and forth in order to do the same operations. I prefer to use either hex or binary since I need to extract certain bytes from the input data string and the hex(int(hex_number, 16)) seems a bit too repetitive and tedious. If I don't convert it to an integer, Python is complaining that it cannot execute the | or ^ on strings.


Solution

  • How about this:

    data = "0x4700ff1de05ca7686c2b43f5e37e6dafd388761c36900ab37"
    size = (len(data)-2)//2
    data_bytes = int(data,16).to_bytes(size,byteorder='big')
    

    Now you can do this:

    data_bytes[4] & data_bytes[5]