Is it possible to do bitwise operations on a string in Python?
What you probably want is the bitstring module (see http://code.google.com/p/python-bitstring/). It seems to support bitwise operations as well as a bunch of other manipulations of bit arrays. But you should be careful to feed bytes into it (e.g. b'abc'
or bytes('abc')
), not characters - characters can contain Unicode and occupy more than one byte.
It doesn't make any sense to do bitwise operations on strings. You probably want to use the struct
module to convert your strings to numbers:
>>> import struct
>>> x = 'abc'
>>> x = '\x00' * (4-len(x)) + x
>>> number = struct.unpack('!i', x)[0]
>>> number
6382179
You can then do all your operations on number
. When (if) you want a string back, you can do struct.pack('!i', number)
.
I wrote a couple functions to convert ascii to int and back using only builtins. I may have mixed up the MSB/LSB though, so I'm using [::-1]
to reverse the input strings. Easy fix if you don't like the ordering.
Enjoy:
>>> intstr = lambda z : ''.join([str(unichr((z & (255*(256**i)))/(256**i))) for i in range(0,((len(bin(z)) - 2) / 8) + (1 if ((len(bin(z)) - 2) / 8) else 0))])
>>> strint = lambda z : reduce(lambda x,y: x | y, [ord(str(z)[i])*((2**8)**i) for i in range(len(str(z)))])
>>> strint('abc'[::-1])
6382179
>>> bin(strint('abc'[::-1]) & 63)
'0b100011'
>>> bin(strint('abc'[::-1]) << 8)
'0b1100001011000100110001100000000'