How To Xor Binary In Python

XOR (Exclusive OR) is a bitwise operator that returns 1 if the bits being compared are different, and 0 if they are the same. In this blog post, we’ll explore how to perform XOR operations on binary numbers using Python. We’ll also learn how to convert integers and strings into binary numbers to work with them.

Performing XOR on Binary Numbers

To perform XOR on two binary numbers in Python, we can use the ^ operator. First, let’s represent our binary numbers as integers. For example, let’s XOR the binary numbers 1101 and 1011:

    a = 0b1101
    b = 0b1011

    result = a ^ b
    print(bin(result))
    

The output of the above code will be 0b110, which is the binary representation of the integer 6. The bin() function is used to convert the integer result of the XOR operation to a binary string.

Converting Integers to Binary

If you want to perform XOR on integers, you’ll first need to convert them to binary. You can use the bin() function for this purpose. Let’s say you have two integers, 13 and 11, and you want to perform XOR on their binary equivalent:

    a = 13
    b = 11

    binary_a = bin(a)
    binary_b = bin(b)

    print(binary_a)
    print(binary_b)
    

The output of the above code will be:

    0b1101
    0b1011
    

Now that we have the binary representation of the integers, we can perform XOR as shown in the previous example.

Converting Strings to Binary

If you want to perform XOR on strings, you’ll first need to convert them to binary. You can use the ord() function to get the ASCII value of a character, and then the bin() function to convert it to binary. Here’s an example of how to convert a string to binary:

    text = "hello"
    binary_text = ""

    for char in text:
        binary_char = bin(ord(char))[2:]
        binary_text += binary_char

    print(binary_text)
    

The output of the above code will be a binary string representing the input text “hello”.

Conclusion

In this blog post, we learned how to perform XOR on binary numbers using the ^ operator in Python. We also explored how to convert integers and strings into binary numbers to work with them. With these skills, you can now implement XOR operations in your own Python projects.