Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

fast XORing bytes in python 3 [duplicate]

I need to xor 2 bytes objects. I use this code:

def bxor(b1, b2): # use xor for bytes
    result = b""
    for b1, b2 in zip(b1, b2):
        result += bytes([b1 ^ b2])
    return result

It works fine when the bytes objects are small, but if I xor big objects (a few MB) it takes very long time (a few hours). How can I make it faster?

like image 817
anton-tsyganenko Avatar asked Apr 26 '14 14:04

anton-tsyganenko


People also ask

Can you XOR bytes Python?

You can use single bytes or multiple byte keys for XOR, and we will use looping to test keys. Here's the XOR truth table: 0 ^ 0 = 0. 0 ^ 1 = 1.

What does bytes () do in Python?

Python bytes() Function The bytes() function returns a bytes object. It can convert objects into bytes objects, or create empty bytes object of the specified size.

How do you XOR two strings in Python?

Use the ^ Operator to Perform the Bitwise Exclusive OR of Two Strings in Python. You can use the ^ operator to perform Bitwise XOR strings in Python.


1 Answers

Adding this in another answer, 'cause it is one:

If you want something faster than the "manual" methods given, there's always Numpy:

import numpy

def bxor_numpy(b1, b2):
    n_b1 = numpy.fromstring(b1, dtype='uint8')
    n_b2 = numpy.fromstring(b2, dtype='uint8')

    return (n_b1 ^ n_b2).tostring()

and it's fast:

first_random = urandom(100000)
second_random = urandom(100000)

min(Timer(partial(bxor_inplace, first_random, second_random)).repeat(10, 100))
#>>> 1.5381054869794752
min(Timer(partial(bxor_append, first_random, second_random)).repeat(10, 100))
#>>> 1.5624085619929247
min(Timer(partial(bxor_numpy, first_random, second_random)).repeat(10, 100))
#>>> 0.009930026979418471

So it's 150x faster than the best alternatives posted here.

like image 132
Veedrac Avatar answered Sep 24 '22 22:09

Veedrac