1

I'm trying to understand the bitwise and the shift operators. I wrote a simple code to show me the bits in a short type.

    class Shift {
    public static void main (String args[]) {
        short b = 16384;

        for (int t = 32768; t > 0; t = t/2) {
            if ((b&t) !=0) System.out.print("1 ");
            else System.out.print ("0 ");
        }
        System.out.println();
        b = b+2;
        for (long t = 2147483648; t > 0; t = t/2) {
            if ((b&t) != 0) System.out.print ("1 ");
            else System.out.print ("0 ");
        }
        System.out.println();
    }
}

The output is:

C:\>javac Shift.java
Shift.java:11: error: integer number too large: 2147483648
                for (long t = 2147483648; t > 0; t = t/2) {
                              ^
1 error

I don't understand why a long type can't hold the value 2147483648.

Thank you for your help.

Thank you for your answers. I changed the code:

    class Shift {
    public static void main (String args[]) {
        short b = 16384;

        for (int t = 32768; t > 0; t = t/2) {
            if ((b&t) !=0) System.out.print("1 ");
            else System.out.print ("0 ");
        }
        System.out.println();
        b = (short)(b+2);
        for (long t = 2147483648L; t > 0; t = t/2) {
            if ((b&t) != 0) System.out.print ("1 ");
            else System.out.print ("0 ");
        }
        System.out.println();
    }
}

And the output is now:

C:\>java Shift
0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 1 0

Why is the output of the second "for" an integer?

Euriloco
  • 253
  • 1
  • 4
  • 9

2 Answers2

3

According to JLS #3.10.1. Integer Literals,

An integer literal is of type long if it is suffixed with an ASCII letter L or l (ell); otherwise it is of type int (§4.2.1).

Hence

long t = 2147483648

Should be

long t = 2147483648L

Where L literal tells the compiler that it's a long value. Otherwise by default compiler treats that as a int value.

Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
  • Thank you. I changed it and it worked. But the output is: C:\>java Shift 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 1 0 Why is the output of the second line a int? – Euriloco Sep 14 '15 at 13:46
2

2147483648 is an int literal, and it's too large for an int. Change it to 2147483648L for a long literal.

Eran
  • 387,369
  • 54
  • 702
  • 768