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

随声附和 提交于 2019-12-05 05:37:23

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'

use eval function to take input of string , all the bitwise operations then you can perform on string .

> t ="1|0"
eval(t)
output: 1
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!