是否可以在Python中对字符串进行按位运算? [英] Is it possible to do bitwise operations on a string in Python?
问题描述
这失败了,不足为奇:
>>> 'abc' << 8
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for <<: 'str' and 'int'
>>>
在ascii abc
等于011000010110001001100011
或6382179
的情况下,是否有办法将其任意移动,以使'abc' << 8
为01100001011000100110001100000000
?
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
?
其他按位运算又如何呢? 'abc' & 63
= 100011
等?
What about other bitwise operations? 'abc' & 63
= 100011
etc?
推荐答案
您可能想要的是位串模块(请参见 http://code.google.com/p/python-bitstring/).它似乎支持按位运算以及其他一些对位数组的操作.但是您应该小心地在其中输入字节(例如b'abc'
或bytes('abc')
),而不要输入字符-字符可以包含Unicode并占用多个字节.
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.
这篇关于是否可以在Python中对字符串进行按位运算?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!