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

旧时模样 提交于 2019-12-07 02:51:45

问题


This fails, not surprisingly:

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

With ascii abc being equal to 011000010110001001100011 or 6382179, is there a way to shift it some arbitrary amount so 'abc' << 8 would be 01100001011000100110001100000000?

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


回答1:


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.




回答2:


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).




回答3:


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'



回答4:


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


来源:https://stackoverflow.com/questions/6279134/is-it-possible-to-do-bitwise-operations-on-a-string-in-python

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