Question

As I noticed, on the one hand, there are bitwise operators in Python, like: 8 ^ 10 which results 2, that's fine. On the other hand, there are ways to convert a base 10 integer to a binary number, e.g. bin(2)

I wonder if I could combine this two, I mean there are no bitwise operators on strings, therefore, bin(8) ^ bin(10) only throws an error. I guess when using bitwise operators on integers, Python's first step is always a conversion anyways.

Actually I was thinking how I could speed up operations like a ^ b when both a and b are high values of integers and there are many bitwise operations on them. Conversion takes too much time so I'd like to just convert them in the first place and manipulating with bitwise operators only after. Maybe converting each number to bool lists could help, but I'm interested if anyone has a better idea.

Thank you very much for any good advices!

Was it helpful?

Solution

You seem to assume that Python internally stores integers as strings of decimal digits. That is completely false. Integers, even arbitrary precision ones (long in 3.x), are stored as bit strings. XORing two Python integers simply performs the native XOR operation on the bits as stored in memory. It loads 2x 64 bits from memory into registers, XORs the bits as efficiently as the CPU allows, and writes the result back to memory. No conversion necessary.

To be completely honest, it does not use some of those 64 bits (this is used for easier overflow detection in multiplication), but it does that by just leaving those bits as zeroes all the time.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top