Search code examples
javabit-manipulationbitvector

what is the value of all 32 bits set to 1 in int?


I was experimenting with bit operations in java

I tried setting bit index by index and this is what I have got. Started setting with 0 th bit in the integer 0 to 31st bit (as int has got 32 bits max)

value  of0bits set: 1
value  of1bits set: 3
value  of2bits set: 7
value  of3bits set: 15
value  of4bits set: 31
value  of5bits set: 63
value  of6bits set: 127
value  of7bits set: 255
value  of8bits set: 511
value  of9bits set: 1023
value  of10bits set: 2047
value  of11bits set: 4095
value  of12bits set: 8191
value  of13bits set: 16383
value  of14bits set: 32767
value  of15bits set: 65535
value  of16bits set: 131071
value  of17bits set: 262143
value  of18bits set: 524287
value  of19bits set: 1048575
value  of20bits set: 2097151
value  of21bits set: 4194303
value  of22bits set: 8388607
value  of23bits set: 16777215
value  of24bits set: 33554431
value  of25bits set: 67108863
value  of26bits set: 134217727
value  of27bits set: 268435455
value  of28bits set: 536870911
value  of29bits set: 1073741823
value  of30bits set: 2147483647
value  of31bits set: -1

Ok great! Value of an int with bits from 0 to 31st index (least to most significant bit) are all set and the result is -1 - from the above result

Let me try the other way:

System.out.println(BitVector.countSetBits( -1 ) )  \\ prints '0'

Then, what is the value of all 32 bits set to 1 in int ?

Added countSetBits function :

   static int countSetBits(int n)
    {
        int count = 0;
        while (n > 0)
        {
            count += n & 1;
            n >>= 1;
        }
        return count;
    }

Solution

  • You can switch all the bits "on" using the ~ operator:

    System.out.println(~0);
    System.out.println("Number of bits set to 1: " + Integer.bitCount(~0));
    

    prints:

    -1
    Number of bits set to 1: 32
    

    Ideone demo


    Your countSetBits doesn't work for 2 reasons:

    1. while (n > 0) won't loop with negative n. Change it to n != 0.
    2. n >>= 1 is signed shifting: this preserves the sign bit as you shift. Change it to n >>>= 1.

    Ideone demo