[issue19251] bitwise ops for bytes of equal length

cowlicks report at bugs.python.org
Sun Jan 10 09:48:47 EST 2016


cowlicks added the comment:

I've attached a diff that adds ^, |, and & to bytes and bytearray object on the master branch (err the analogous hg thing).

It also includes a test file which definitely is in the wrong place, but demonstrates what is working.

Personally this came up while I was playing with toy crypto problems. I expected to already be part of the language, but it wasn't. I think this is a natural expectation. I don't think it is obvious to newer python users that they need to cast bytes to ints to do bitwise operations on them.

And I do not understand how bitwise operations work on arbitrary precision integers. So perhaps it is not as simple of a concept as "bytes xor bytes".

Some folks have suggested using NumPy, but that is a very heavy dependency, and not useful outside of cpython.

I searched for code this would clean up in the wild. It was easy to find.

This would also catch bugs when bytes objects are different lengths, but there is no check. Like this code I found 

# XOR each byte of the roundKey with the state table
def addRoundKey(state, roundKey):
    for i in range(len(state)):
        state[i] = state[i] ^ roundKey[i]

p.s. this is my first cpython issue/patch please let me know if I'm doing something wrong.

----------
keywords: +patch
nosy: +cowlicks
Added file: http://bugs.python.org/file41569/bitwise_bytes.diff

_______________________________________
Python tracker <report at bugs.python.org>
<http://bugs.python.org/issue19251>
_______________________________________


More information about the Python-bugs-list mailing list