Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reverse bitwise AND (&) in C?

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?

like image 697
VaioIsBorn Avatar asked Apr 02 '10 10:04

VaioIsBorn


People also ask

What is the reverse of Bitwise and?

Note that both AND ( & ) and OR ( | ) are destructive. The only Boolean operations that are reversible are XOR ( ^ ) and NOT ( ~ ).

How do I revert Bitwise or operation?

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).

Is Bitwise and reversible?

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.


2 Answers

Bitwise & can't be reversed:

0 & 1 = 0
0 & 0 = 0
like image 92
Andrey Avatar answered Sep 24 '22 12:09

Andrey


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 (~).

like image 31
Paul R Avatar answered Sep 24 '22 12:09

Paul R