", ...">

Is it possible to perform bitwise operations on a string in Python?

No wonder:

>>> 'abc' << 8 Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: unsupported operand type(s) for <<: 'str' and 'int' >>> 

If ascii abc is 011000010110001001100011 or 6382179 , is there any way to shift it by an arbitrary amount, so 'abc' << 8 will be 01100001011000100110001100000000 ?

What about other bitwise operations? 'abc' & 63 = 100011 etc.

+7
source share
4 answers

Maybe you need a bit string module (see http://code.google.com/p/python-bitstring/ ). It seems to support bitwise operations, as well as many other bitmap manipulations. But you must be careful to insert bytes into it (for example, b'abc' or bytes('abc') ), and not characters - characters can contain Unicode and occupy more than one byte.

+8
source

It does not make sense to do bitwise operations on strings. You probably want to use the struct module to convert strings to numbers:

 >>> import struct >>> x = 'abc' >>> x = '\x00' * (4-len(x)) + x >>> number = struct.unpack('!i', x)[0] >>> number 6382179 

Then you can do all your operations on number . When (if) you want to return a string, you can do struct.pack('!i', number) .

+7
source

I wrote several functions for converting ascii to int and vice versa, using only the built-in ones. Maybe I messed up MSB / LSB, so I use [::-1] to change the input lines. Easy to fix if you don't like the order.

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' 
+2
source

use the eval function to get string input, all the bitwise operations that can then be performed on the string.

 > t ="1|0" eval(t) output: 1 
0
source

Source: https://habr.com/ru/post/890057/


All Articles