Invert bitwise left shift and OR assignment

What would be the inverse function for this?

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

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

+7
c ++ c bit-manipulation bit-shift or-operator
source share
2 answers

You cannot completely restore all bits.

B << 3 moves β€œB” three bits to the left, and it does not spin around. This means that the state of the top three bits of B is erased - if you do not know this, you cannot restore B.

Example:

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

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

| 0x07 | 0x07 fills the lower three bits (with 111 ), so even if you did not shift, you will erase the lower three bits with 111 , making these bits irrevocable.

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

A ^ same-value can cancel with another A ^ same-value , because ((A ^ B) ^ B) == A

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

A | same-value A | same-value also cannot cancel with AND: A & same-value

But the shift will still cause problems, even if it was XOR'd (which is not the case).

+15
source share

Given (using 8-bit B as an example, using 0b for binary form, just a demo)

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

You can get the same A , so I don’t think you can cancel the calculation, the leftmost 3 bits will be lost.

+1
source share

All Articles