Skip to content

Instantly share code, notes, and snippets.

@evandrix
Created November 1, 2012 07:20
Show Gist options
  • Save evandrix/3992302 to your computer and use it in GitHub Desktop.
Save evandrix/3992302 to your computer and use it in GitHub Desktop.
Fastest bitwise xor between two multibyte binary data variables
def xor(data, key):
import numpy, math
# key multiplication in order to match the data length
key = (key*int(math.ceil(float(len(data))/float(len(key)))))[:len(data)]
# Select the type size in bytes
for i in (8,4,2,1):
if not len(data) % i: break
if i == 8: dt = numpy.dtype('<Q8');
elif i == 4: dt = numpy.dtype('<L4');
elif i == 2: dt = numpy.dtype('<H2');
else: dt = numpy.dtype('B');
return numpy.bitwise_xor(numpy.fromstring(key, dtype=dt), numpy.fromstring(data, dtype=dt)).tostring()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment