2

I am trying to translate Java code with logical right shift (>>>) (Difference between >>> and >>) to C#

Java code is

 return hash >>> 24 ^ hash & 0xFFFFFF;

C# is marked >>> as syntax error.

How to fix that?

Update 1 People recommend to use >> in C#, but it didn't solve problem.

System.out.println("hash 1 !!! = " + (-986417464>>>24));

is 197

but

Console.WriteLine("hash 1 !!! = " + (-986417464 >> 24));

is -59

Thank you!

Community
  • 1
  • 1
Arthur
  • 2,993
  • 6
  • 37
  • 72
  • Possible duplicate of [Equivalent of Java triple shift operator (>>>) in C#?](http://stackoverflow.com/questions/1880172/equivalent-of-java-triple-shift-operator-in-c) – Brian Jan 19 '17 at 13:58
  • Also [What is the C# equivalent of Java unsigned right shift operator >>>](http://stackoverflow.com/q/8125127/18192) – Brian Jan 19 '17 at 14:06

2 Answers2

17

Java needed to introduce >>> because its only unsigned type is char, whose operations are done in integers.

C#, on the other hand, has unsigned types, which perform right shift without sign extension:

uint h = (uint)hash;
return h >> 24 ^ h & 0xFFFFFF;
Sergey Kalinichenko
  • 697,062
  • 78
  • 1,055
  • 1,465
  • No, it is not. For example System.out.println("hash 2 !!! = " + (-986417464>>>24)); is 197 but Console.WriteLine("hash 1 !!! = " + (-986417464 >> 24)); is -59 – Arthur Jan 19 '17 at 12:34
  • But why it is not equal in my example Console.WriteLine("hash 1 !!! = " + (-986417464 >> 24)); ? – Arthur Jan 19 '17 at 12:43
  • 1
    @ArthurKhusnutdinov Because you are shifting an `int`, not a `uint`. `-986417464` is `int` by default. You need to add a cast ([link](http://ideone.com/N7ze1W)). – Sergey Kalinichenko Jan 19 '17 at 12:48
0

For C# you can just use >>

If the left-hand operand is of type uint or ulong, the right-shift operator performs a logical shift: the high-order empty bit positions are always set to zero.

From the docs.

General Grievance
  • 4,259
  • 21
  • 28
  • 43
Christiaan
  • 183
  • 11