[Python-ideas] String and bytes bitwise operations

INADA Naoki songofacandy at gmail.com
Fri Jun 22 07:08:11 EDT 2018


Bitwise xor is used for "masking" code like these:

https://github.com/PyMySQL/PyMySQL/blob/37eba60439039eff17b32ef1a63b45c25ea28cec/pymysql/connections.py#L139-L146
https://github.com/tornadoweb/tornado/blob/0b2b055061eb4754c80a8d6bc28614b86954e336/tornado/util.py#L470-L471
https://github.com/tornadoweb/tornado/blob/master/tornado/speedups.c#L5

I think implementing it in C is really helpful for protocol library authors.

On Thu, May 17, 2018 at 7:54 PM Ken Hilton <kenlhilton at gmail.com> wrote:

> Hi all,
>
> We all know the bitwise operators: & (and), | (or), ^ (xor), and ~ (not).
> We know how they work with numbers:
>
> 420 ^ 502
>
> 110100100
> 111110110
> == XOR ==
> 001010010
> = 82
>
> But it might be useful in some cases to (let's say) xor a string (or
> bytestring):
>
> HELLO ^ world
>
> 01001000 01000101 01001100 01001100 01001111
> 01110111 01101111 01110010 01101100 01100100
> =================== XOR ====================
> 00111111 00101010 00111110 00100000 00101011
> = ?*> +
>
> Currently, that's done with this expression for strings:
>
>     >>> ''.join(chr(ord(a) ^ ord(b)) for a, b in zip('HELLO', 'world'))
>     '?*> +'
>
> and this expression for bytestrings:
>
>     >>> bytes(a ^ b for a, b in zip(b'HELLO', b'world'))
>     b'?*> +'
>
> It would be much more convenient, however, to allow a simple xor of a
> string:
>
>     >>> 'HELLO' ^ 'world'
>     '?*> +'
>
> or bytestring:
>
>     >>> b'HELLO' ^ b'world'
>     b'?*> +'
>
> (All of this applies to other bitwise operators, of course.)
> Compatibility issues are a no-brainer - currently, bitwise operators for
> strings raise TypeErrors.
>
> Thanks.
>
> Suggesting,
> Ken
> ​ Hilton​
> ;
> _______________________________________________
> Python-ideas mailing list
> Python-ideas at python.org
> https://mail.python.org/mailman/listinfo/python-ideas
> Code of Conduct: http://python.org/psf/codeofconduct/
>


-- 
INADA Naoki  <songofacandy at gmail.com>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20180622/cc2962f4/attachment.html>


More information about the Python-ideas mailing list