Indeed, the four bitwise operations (&, ^, !, |
) can be represented as mathematical functions. This is probably not original data, but I haven't found it represented this way anywhere else on the Stack Exchange.
Let us start by finding the formula for x & y
, the simplest of the four.
First, we need a way of comparing the bits of the two numbers, which must return $1$ if both numbers are $1$ and $0$ otherwise. Then, we will need a way to convert these numbers back into the binary, and by extension base $10$, result. The second is simple: multiplication of the two numbers. The third is also simple; we multiply each result by $2^n$ with an incremented $n$, and sum the results (exactly how binary numbers are formed). So already, we suspect that the formula will look something like:
$$
\sum_{n=0}^{b}2^n[f(x)][f(y)]
$$
Where $b$ is the number of bits of which the number is composed, and $f$ yields the value of the $n$th decimal place when its argument is written in binary. Now, how can we reduce a number to its bits? Simple: we divide it by the same $2^n$ by which we later multiply, discard the remainder with the floor function, and do a modulo 2 operation to reduce the number to bits. So the final formula is:
$$
x\text{ & }y = \sum_{n=0}^{b}2^n\left(\left\lfloor\frac{x}{2^n}\right\rfloor \bmod 2\right)\left(\left\lfloor\frac{y}{2^n}\right\rfloor \bmod 2\right)
$$
One would think that since multiplication is equivalent to a logical $\land$ AND, one need only change this formula to an addition-based format to gain the formula for x | y
. However,
$$
\sum_{n=0}^{b}2^n\left[\left[\left(\left\lfloor\frac{x}{2^n}\right\rfloor \bmod 2\right) + \left(\left\lfloor\frac{y}{2^n}\right\rfloor \bmod 2\right)\right]\bmod 2\right]
$$
does not yield OR, but XOR ^
. This is because if both bits are $1$, they sum to $2$, and $2 \bmod 2 = 0$.
Now we can move to NOT. The operation to reverse bits is simple, $(x + 1) \bmod 2$. Building on the idea of how we obtain each bit from $\left\lfloor\frac{x}{2^n}\right\rfloor \bmod 2$, we find that !x
is equivalent to:
$$
\sum_{n=0}^{b}2^n\left[\left(\left\lfloor\frac{x}{2^n}\right\rfloor \bmod 2 + 1\right) \bmod 2\right]
$$
The last and most difficult of the four is OR. I will leave its derivation as an exercise to the reader, but the formula is
$$
x\text{ | }y = \sum_{n=0}^{b}2^n\left[\left[\left(\left\lfloor\frac{x}{2^n}\right\rfloor \bmod 2\right) + \left(\left\lfloor\frac{y}{2^n}\right\rfloor \bmod 2\right) + \left(\left\lfloor\frac{x}{2^n}\right\rfloor \bmod 2\right)\left(\left\lfloor\frac{y}{2^n}\right\rfloor \bmod 2\right)\bmod 2\right]\bmod 2\right]
$$