[Python-ideas] String and bytes bitwise operations
Ken Hilton
kenlhilton at gmail.com
Thu May 17 06:53:32 EDT 2018
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
;
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20180517/81df5f41/attachment.html>
More information about the Python-ideas
mailing list