Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 373
n.r. Avatar asked Jul 25 '13 01:07

n.r.


2 Answers

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

like image 119
Jamin Grey Avatar answered Sep 22 '22 14:09

Jamin Grey


Given (Using 8-bit B as example, using0b for binary form, demonstration only)

B = 0b00000000
B = 0b00100000
//...
B = 0b11100000

You can get the same A, so I don't think you can reverse the calculation, the leftmost 3 bits are lost.

like image 44
Yu Hao Avatar answered Sep 22 '22 14:09

Yu Hao