Search code examples
c++cbit-manipulationbit-shiftor-operator

Invert a bitwise left shift and OR assignment


What would be the inverse function for this?

A = (B << 3) | 0x07;

How can I get a B when I already have the corresponding A?


Solution

  • You can't ever recover all the bits fully.

    B << 3 shifts 'B' three bits to the left, and it doesn't loop around. This means the state of the top three bits of B are erased - unless you know those, you wouldn't be able to recover B.

    Example:

    10101101 << 3
    
    Turns: 10101101
              ^---^
    Into:  01101000
           ^---^
    

    The top three bits are lost, and the bottom three are filled with zeroes. Deleted data is deleted.

    The | 0x07 fills the bottom three bits (with 111), so even if you didn't shift, you'd be erasing the lowest three bits with 111, making those bits irrecoverable.

    Now if it was XOR'd instead of OR'd, it'd be recoverable with another XOR:

    A ^ same-value can be undone with another A ^ same-value because ((A ^ B) ^ B) == A

    A | same-value cannot be undone with another A | same-value

    A | same-value also cannot be undone with an AND: A & same-value

    But the shift still would cause problems, even if it was XOR'd (which it isn't).