在Python中使用二进制运算符..如果(c1>;=“xc0&”&;c1<;=“xdf”)则进行翻


using binary operator in Python... translating if (c1 >= "xc0" & c1 <= "xdf")

我正在将一个外部类从PHP转换为Python,它会做一些技巧,比如:

if ($c1 >= "'xc0" & $c1 <= "'xdf")
[...]
$cc1 = (chr(ord($c1) / 64) | "'xc0");
[...]
$cc2 = ($c1 & "'x3f") | "'x80";

其中$c1、^$cc1、$cc2是字符

我刚刚意识到,我不能把它和python一起使用,因为字符是字符串,而不是被重复地视为"字符的二进制表示",其中运算符&并且|有意义。。。

请问,你会如何用Python的方式翻译这些?

>>> c1 = "a"
>>> (c1 & "'x3f") | "'x80"
Traceback (most recent call last):
  File "<pyshell#202>", line 1, in <module>
    (c1 & "'x3f") | "'x80"
TypeError: unsupported operand type(s) for &: 'str' and 'str'

EDIT:实际上,这个PHP类似乎不起作用,所以它也不适合我的需求。非常感谢你的帮助。

使用ord函数获取值,然后使用实际数字进行屏蔽。

>>> c1 = "a"
>>> (ord(c1) & 0x3f) | 0x80
161
>>> hex((ord(c1) & 0x3f) | 0x80)
'0xa1'

这是一个原始的UTF-8编码函数。

c1.encode('utf-8')

请注意,除非您本机使用unicode(为什么不使用呢?),否则您需要首先从'latin-1'进行解码。

Python 2.7.3 (default, Sep 26 2012, 21:51:14) 
>>> c1 = 'd'
>>> # if ($c1 >= "'xc0" & $c1 <= "'xdf")
... 
>>> ord(c1) >= 0xc0 and ord(c1) <= 0xdf
False
>>> # $cc1 = (chr(ord($c1) / 64) | "'xc0");
... 
>>> chr(ord(c1) / 64 | 0xc0)
''xc1'
>>> # $cc2 = ($c1 & "'x3f") | "'x80";
... 
>>> ord(c1) & 0x3f | 0x80
164
>>>