0
public static void main(String[] args) {
        
        long x = 164997969936395L;
        
        int a = (int)(x >>> 16);
        
        System.out.println(a); //Prints -1777298077

        long b = (x >>> 16);
        
        System.out.println(b); //Prints 2517669219
        
    }

Trying to bitshift x by 16 bits, but the output differs depending on whether i use a long or an int, also it seems when i use long the negative signs are always gone.

I've also noticed when using int it really is divided by 2^16 whereas using long it is not, what's happening there?

Progman
  • 16,827
  • 6
  • 33
  • 48

1 Answers1

2

In the first case, 2517669219, which is x >>> 16, is narrowed down to an int.

int can represent values in the range [-2147483648, 2147483647].
2517669219 is greater than 2147483647, so overflow happens.

spongebob
  • 8,370
  • 15
  • 50
  • 83