-2

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;
    }
Athul Muralidharan
  • 563
  • 1
  • 7
  • 15

3 Answers3

3

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

Andy Turner
  • 122,430
  • 10
  • 138
  • 216
1

The value is, as described here at MSDN - UInt32.MaxValue Field:

The value of this constant is 4,294,967,295;
that is, hexadecimal 0xFFFFFFFF.

You have been using an Int32(which is signed). Hence you got a -1 at the last factor.

So if all bits are set to 1 the integer value 0xFFFFFFFFwill be

  • -1 for signed 32-bit integer
  • 4,294,967,295 for unsigned 32-bit integer
zx485
  • 24,099
  • 26
  • 45
  • 52
1

As others have already noted, -1 is the correct interpretation of this 32-bit signed integer. This is because this is in two's-complement notation, in which the bit-patterns 0 to 2^31-1 (inclusive) are positive, and bit-patterns 2^31 to 2^32-1 (inclusive) are treated as negative. These negative numbers are actually the given number plus 2^32. Thus a number with all 32 bits set to 1 is equivalent to -1.

rwp
  • 1,456
  • 2
  • 9
  • 21