Georgi Stoyanov
Georgi Stoyanov

Reputation: 644

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.

Upvotes: 1

Views: 1536

Answers (2)

Yakov Dan
Yakov Dan

Reputation: 3347

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]

Upvotes: 2

user10054228
user10054228

Reputation:

As you mentioned, the problem is that strings of hex digits are more readable and good for slicing and at least some shifting operations, but don't support bitwise operations. On the other hand, integers support bitwise operations but no slicing. The closest to what you want may be to create a custom class implementing both features (doing conversion whenever needed). This won't save you from implementing (and executing) the more complex code, but the rest of your application may be more readable because the conversions are "hidden".

Upvotes: 2

Related Questions