簡體   English   中英

是否可以對 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等於0110000101100010011000116382179 ,有沒有辦法將其移動一些任意數量,所以'abc' << 8將是01100001011000100110001100000000

其他按位運算呢? 'abc' & 63 = 100011等等?

您可能想要的是位串模塊(請參閱http://code.google.com/p/python-bitstring/ )。 它似乎支持按位操作以及對位 arrays 的一系列其他操作。 但是您應該小心將字節輸入其中(例如b'abc'bytes('abc') ),而不是字符 - 字符可以包含 Unicode 並占用超過一個字節。

對字符串進行按位運算沒有任何意義。 您可能想使用struct模塊將字符串轉換為數字:

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

然后,您可以對number進行所有操作。 當(如果)你想要一個字符串回來時,你可以做struct.pack(',i', number)

我編寫了幾個函數來僅使用內置函數將 ascii 轉換為 int 並返回。 我可能混淆了 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'

使用 eval function 輸入字符串,然后您可以對字符串執行所有按位運算。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM