Friday 1 July 2011

Java int and short casting

Did some test on Java int and short casting. I'm interested to see how it behaves when the integer overflows short.

public class CastingTest {
  public static void test(int a) {
    System.out.println("a = " + a + " (" + getBits(a) + ")");
    short b = (short) a;
    System.out.println("b = " + b + " (" + getBits(b) + ")");
    int c = b;
    System.out.println("c = " + c + " (" + getBits(c) + ")");
    int d = b & 0xffff;
    System.out.println("d = " + d + " (" + getBits(d) + ")");
  }
  
  public static String getBits(int v) {
    StringBuffer sb = new StringBuffer(32 + 3);
    for (int i = 1; i <= 32; i++) {
      int mask = 1 << 31;
      int bit = (v & mask) == 0 ? 0 : 1; 
      sb.append(bit);
      if (i % 8 == 0 && i != 32)
        sb.append(' ');
      v <<= 1;
    }
    return sb.toString();
  }
  
  public static String getBits(short v) {
    StringBuffer sb = new StringBuffer(16 + 1);
    for (int i = 1; i <= 16; i++) {
      int mask = 1 << 15;
      int bit = (v & mask) == 0 ? 0 : 1; 
      sb.append(bit);
      if (i % 8 == 0 && i != 16)
        sb.append(' ');
      v <<= 1;
    }
    return sb.toString();
  }
  
  public static void main(String[] args) {
    test(65535);
    test(65536);
    test(-65535);
  }
}

Output:

a = 65535 (00000000 00000000 11111111 11111111)
b = -1 (11111111 11111111)
c = -1 (11111111 11111111 11111111 11111111)
d = 65535 (00000000 00000000 11111111 11111111)

a = 65536 (00000000 00000001 00000000 00000000)
b = 0 (00000000 00000000)
c = 0 (00000000 00000000 00000000 00000000)
d = 0 (00000000 00000000 00000000 00000000)

a = -65535 (11111111 11111111 00000000 00000001)
b = 1 (00000000 00000001)
c = 1 (00000000 00000000 00000000 00000001)
d = 1 (00000000 00000000 00000000 00000001)

This shows that, when converting int to short, jvm just takes the lower two bytes, even if the number overflows short.

No comments :

Post a Comment