[Python-ideas] String and bytes bitwise operations

Stephan Houben stephanh42 at gmail.com
Thu May 17 07:06:59 EDT 2018

```Seems you want numpy:

>>> import numpy
>>> numpy.frombuffer(b"Hello", dtype=numpy.uint8) ^
numpy.frombuffer(b"World", dtype=numpy.uint8)
array([31, 10, 30,  0, 11], dtype=uint8)

Stephan

2018-05-17 12:53 GMT+02:00 Ken Hilton <kenlhilton at gmail.com>:

> 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/
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20180517/2f07b36d/attachment.html>
```