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?
Asked
Active
Viewed 855 times
2
-
possible duplicate of [How to use the unsigned integer in java 8?](http://stackoverflow.com/questions/25556017/how-to-use-the-unsigned-integer-in-java-8) – Keegan May 15 '15 at 15:19
-
to shift unsigned, use `>>>` – phuclv May 15 '15 at 16:24
1 Answers
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