Is there an existing Python library that directly supports all binary bitwise operations with ints?
Python has binary bitwise operations “and” (a & b), “xor” (a ^ b), “or” (a | b) and unary “not” (~ a). Formulas like (a & ~b), (a | ~b), (a ^ ~b), ~(a & b), ~(a | b) involve two or more operations and are less efficient. I’m looking for an existing library that has a single operation for each of them with (a & ~b) is as fast as (a & b) and so on.
mezzoctane is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
6
Python’s built-in bitwise operators are quite efficient when compared to others. Python’s built-in bitwise operations (like a & ~b) are already highly optimized. The Python interpreters and the underlying C implementatian handle these operations very efficiently and Compound bitwise operation like a & ~b are typically optimized by modern compilers and processors. The CPU often can perform these operations in a single instruction or cycle
If you want to explore libs try numpy
import numpy as np
def and_not(a, b):
return np.bitwise_and(a, np.bitwise_not(b))
def or_not(a, b):
return np.bitwise_or(a, np.bitwise_not(b))
...
Note that In-Built functions typically optimized by the Python interpreter and underlying CPU instructions will stands them faster…
4