2

I understand that java has no unsigned int, however as of Java SE 8, there are methods to use integer datatype to perform unsigned arithmetic. How do I go about doing bits shift to "unsigned int" in java?

Steve Kuo
  • 61,876
  • 75
  • 195
  • 257
geeceekay
  • 67
  • 8

1 Answers1

2

You do all bitwise operations the same way you do them for signed int, using >>> to shift right. "Unsigned" features serve just for outputting and converting, they don't affect inner bit representation.

For example:

int i = Integer.MAX_VALUE / 1024 - 1023;
System.out.println(Integer.toUnsignedString(i) + "=" + Integer.toBinaryString(i));
i = i >>> 10;
System.out.println(Integer.toUnsignedString(i) + "=" + Integer.toBinaryString(i));
i = i << 21;
System.out.println(Integer.toUnsignedString(i) + "=" + Integer.toBinaryString(i));

resulting output:

2096128=111111111110000000000                // 11 ones, 10 zeros
2047=11111111111                             // 11 ones, 0 zeros
4292870144=11111111111000000000000000000000  // 11 ones, 21 zeros
Alex Salauyou
  • 14,185
  • 5
  • 45
  • 67