17

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?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
VaioIsBorn
  • 7,683
  • 9
  • 31
  • 28

4 Answers4

32

Bitwise & can't be reversed:

0 & 1 = 0
0 & 0 = 0
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Andrey
  • 59,039
  • 12
  • 119
  • 163
21

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

Paul R
  • 208,748
  • 37
  • 389
  • 560
5

Impossible. Bitwise & of 0xff000000 is a lossy operation. You lose the lower 24-bits permanently.

richb
  • 4,716
  • 5
  • 24
  • 22
4

You can only reverse XOR, as it's non-destructive.

Both OR and AND are destructive.

Steffen
  • 13,648
  • 7
  • 57
  • 67