Created
November 1, 2012 07:20
-
-
Save evandrix/3992302 to your computer and use it in GitHub Desktop.
Fastest bitwise xor between two multibyte binary data variables
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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