0

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"]
2
  • How "0011" + "0101" becomes "0110" ? Commented Jan 25, 2017 at 16:32
  • Are you looking to concatenate byte arrays or to add binary values? Commented Jan 25, 2017 at 16:59

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.