0

I have the below code and I can't understand why the last line doesn't return 77594624. Can anyone help me write the inverse bitwise operation to go from 77594624 to 4 and back to 77594624?

        Console.WriteLine(77594624);
        Console.WriteLine((77594624 >> 24) & 0x1F);
        Console.WriteLine((4 & 0x1F) << 24);
akanieski
  • 61
  • 5
  • 5
    Once you right shift all the bits away, there's no way to recover them. – ggorlen Jul 18 '20 at 21:51
  • 2
    You should do "circular shift" check it here: https://stackoverflow.com/a/185743/168941 – Cihan Yakar Jul 18 '20 at 21:55
  • There is no way to invert this. For example, `(83886079 >> 24) & 0x1F` also equals `4`, and so does `(77594625 >> 24) & 0x1F`. In those examples, I replaced `77594624` with a different number, but the operation had the same result of `4`. If the operation was invertible, only one value of `x` would map `f(x) = (x >> 24) & 0x1F` to `4`. – dannyadam Jul 18 '20 at 23:13

2 Answers2

3

When you bit shift a value you might "lose" bits during that operation. If you right shift the value 16, which is 0b10000 in binary, by 4, you will get 1.

0b10000 = 16
0b00001 = 1

But this is also the case for other numbers like 28, which is 0b11100.

0b11100 = 28 = 16 + 8 + 4
0b00001 = 1

So with the start point 1 you cannot go "back" to the original number by left shifting again, as there is not enough information/bits available, you don't know if you want to go back to 16 or 28.

Progman
  • 16,827
  • 6
  • 33
  • 48
0

77594624 looks like this in binary, and the x's mark the part that is extracted by the right shift and bitwise AND:

000001000101000000000000000000000
   xxxxx

Clearly some information is lost.

If the other parts of the number were available as well, then they could be reassembled.

harold
  • 61,398
  • 6
  • 86
  • 164