Sidharth Ghoshal
Sidharth Ghoshal

Reputation: 720

Bitwise treatment of objects in python

So I was attempting to a bitwise "XOR" between two objects in python, as part of an xor-swap routine (just as a demonstrative example). But I noticed that the bitwise xor doesn't work on strings.

I did some exploring on stackoverflow and came across:

Bitwise xor python

The answer is unsatisfactory, namely because I want to be able to do, raw byte level manipulation with my data. Is this simply impossible in python?

I'm hoping someone can point me to a library that will let me be able to treat all objects as blocks of bytes that I am free to manipulate with familiar operators such as "xor"

Upvotes: 2

Views: 808

Answers (2)

Mark Tolonen
Mark Tolonen

Reputation: 177516

Strings are immutable in Python. You want the bytearray type to manipulate data in place.

>>> b = bytearray([1,2,3,4,5,6,7,8])
>>> for i in xrange(len(b)):
...   b[i] ^= 255
...
>>> b
bytearray(b'\xfe\xfd\xfc\xfb\xfa\xf9\xf8\xf7')

Upvotes: 2

Paulo Scardine
Paulo Scardine

Reputation: 77251

Strings are not byte arrays in Python, like they are in C. Internally they are UTF-32 (UCS-4) IINM.

Python is very hackable. If something is not there, you can bend it to do what you want most of the time:

>>> class MyBytes(bytes):
...     def __xor__(self, v):
...         return bytes(a ^ b for a, b in zip(self, v))
...
>>> MyBytes('!7-x9*=x9x49"!x:*9,', 'ascii') ^ MyBytes('XXXXXXXXXXXXXXXXXXX', 'ascii')
b'you are a lazy brat' 

This is Python 3, I guess you can figure out how to do that in earlier versions.

Upvotes: 0

Related Questions