What is the difference between shr() and ushr() named functions in Kotlin

Viewed 502

Difference of a.shr(b) and a.ushr(b) functions in the Kotlin language.When use both the functions I'm getting same output so please help in to know the difference between these functions

1 Answers
  • shr shifts your bits to right
  • ushr also shift right, but fills up the most left bit with zero

If you're only doing bit shifts on positive values, there is no difference. If you're also doing it on negative values, there is a big difference.

                 Int          Binary
                 -63532       11111111111111110000000000000100    
-63532 ushr 1    2147450882   01111111111111111000000000000010
-63532 shr 1     -32766       11111111111111111000000000000010
                              ^
                              |
                          Difference

In this case, the ushr will flip the left most bit so you're now having a positive value.

Related