Nice1013
Nice1013

Reputation: 125

In python, Is there any way to add two Byte arrays together like binary strings?

Is there any python packages for adding byte arrays together just like adding binary strings together.

For instance:

"0011" + "0101" = "0110"

but only with bytes.

I tried to convert the bytes to strings but its too much work for the computer. It would be easier to just add bytes together.

Bytearray1["10000011", "00000000"] 
+
Bytearray2["10000101", "00000000"]
=
Bytearray3["00000110", "00000001"]

Upvotes: 0

Views: 1377

Answers (1)

DRPK
DRPK

Reputation: 2091

You need to use bitwise operators. In your particular case you need XOR (bitwise exclusive or). In python XOR is denoted by ^.

Look at the example below:

a = int('0011', 2)
b = int('0101', 2)
c = a^b  
binary_rep = '{:04b}'.format(c)  # convert integer to binary format (contains 4 digits with leading zeros)
print(binary_rep)

The above code prints out '0110' to the screen.

You can also define your own function as follows:

def XOR(x, y, number_of_digits):
    a = int(x, 2)
    b = int(y, 2)
    c = a^b  
    format_str = '{:0%db}' % number_of_digits
    binary_rep = format_str.format(c) 
    return binary_rep

Upvotes: 1

Related Questions