Search code examples
javabit

Which bit is the higher order bit in int type in java?


I read that in java, negative integers are obtained by taking 2's complement of a positive integer. In short, it also means that the higher order bit is being set to 1 in order to convert a positive integer to negative integer. Out of curiosity I tried figuring out exactly which bit in an integer acts as the higher order bit in java. Now, the limit of integers in java is -(2^32) to ((2^32) - 1). So I decided if I keep on checking each of the 32 bit positions, I will come to know which one is the higher order bit.
Following is the code I used.

public class Main
{
   public static void main(String[] args) {
      int x = 5;
      for(int i = 0; i<32; i++) {
        if((x|(1<<i)) == -5) {
            System.out.println(i + "th bit is the higher order bit");
        }
      }
   }
 }

But none of the bits came out to be the higher order bit. Which bit is it?


Solution

  • If you'll print the binary representation of 5and -5:

    System.out.println (Integer.toBinaryString (5));
    System.out.println (Integer.toBinaryString (-5));
    

    You'll get:

    101
    11111111111111111111111111111011
    

    or, if we add the leading 0s:

    00000000000000000000000000000101
    11111111111111111111111111111011
    

    As you can see, the 2 representations differ in more than just the sign bit (which is the left most bit). Therefore your code is incorrect.

    Setting the sign bit of the binary representation of 5:

    System.out.println (5|(1<<31));
    

    doesn't result in -5, it results in:

    -2147483643