How to reverse bitwise AND (&) in C?
For example I have an operation in C like this:
((unsigned int)ptr & 0xff000000))
The result is 0xbf000000. What I need at this moment is how to reverse the above, i.e. determine ptr by using the result from the operation and of course 0xff000000.
Is there any simple way to implement this in C?
Note that both AND ( & ) and OR ( | ) are destructive. The only Boolean operations that are reversible are XOR ( ^ ) and NOT ( ~ ).
If C=A|B , then wherever you have a 1 in C and a 1 in B, the corresponding bit of A could have been either 0 or 1. In your example, 93|199=223, but 92|199 is also 223. So, given 223 and 199 there's no single answer (in fact, in this example there are 32 possible answers).
By a similar argument, bitwise OR (the | operator) is also irreversible. On the other hand, bitwise XOR (the ^ operator) is reversible. As a concrete example, if for 1-bit numbers, c is 1 and a is 1, then b could be either 0 or 1.
Bitwise & can't be reversed:
0 & 1 = 0
0 & 0 = 0
You can't do that because you have thrown away information (i.e. bits) - you can't get information back from nowhere.
Note that both AND (&) and OR (|) are destructive. The only Boolean operations that are reversible are XOR (^) and NOT (~).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With