在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
呢?
那其他的位运算呢?比如 'abc' & 63
会等于 100011
之类的结果吗?
4 个回答
3
我写了几个函数,用来把ascii码转换成整数,然后再转换回来,都是用的内置功能。不过我可能把最高有效位(MSB)和最低有效位(LSB)搞混了,所以我用 [::-1]
来反转输入的字符串。如果你不喜欢这个顺序,改起来很简单。
希望你喜欢:
>>> 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'
7
对字符串进行位运算是没有意义的。你可能想用 struct
模块把字符串转换成数字:
>>> import struct
>>> x = 'abc'
>>> x = '\x00' * (4-len(x)) + x
>>> number = struct.unpack('!i', x)[0]
>>> number
6382179
然后你就可以对 number
进行所有的操作了。当你想要把结果再变回字符串时,可以使用 struct.pack('!i', number)
。
10
你可能想要的是 bitstring 模块(可以查看 http://code.google.com/p/python-bitstring/)。这个模块似乎支持位运算,还有很多其他对比特数组的操作。不过,你要注意输入的数据要是字节(比如 b'abc'
或 bytes('abc')
),而不是字符——因为字符可能包含 Unicode,可能会占用多个字节。