Java Reference
In-Depth Information
the result with a single operation. It may well be faster than you could implement it for yourself, too. Let's
consider some examples of how you use these methods.
First, suppose you define an integer variable as follows:
int data = 0x0F00; // data is: 0b0000_0000_0000_0000_0000_1111_0000_0000
You can now apply the
bitCount()
method to this. You must use the method in the
Integer
class be-
cause
data
is of type
int
:
int bits = Integer.bitCount(data); // Result is 4
The variable
bits
is set to 4 because
data
contains four 1 bits.
Here's a definition of another integer variable, this time of type
long
:
long number = 0xF000_0000_0000_000FL;
The bit pattern in
number
has the first byte as 1111 0000 and the last byte as 0000 1111; all the other bytes
are zero. Note that the
L
on the end of the literal is essential here. Without it you are specifying a literal of
type
int
, and type
int
only has 32 bits so you get an error message from the compiler.
You could rotate the bits in
number
left by two with the following statement:
long result = Long.rotateLeft(number, 2);
The variable
result
are set to a value where the first byte is 0xC0, the last byte is 0x3F, and all the other
bits are zero. The bits in
number
are shifted left by two bit positions, and the two 1 bits that are shifted out
on the left are shifted in on the right as this is a rotation operation on the bits.
Let's see some of these methods working for real.
TRY IT OUT: Methods for Operations on Bits
You can see the effects of some of the methods I have discussed by just outputting the results of some of
the operations. The example also makes use of another static method that is defined in both the
Integer
and
Long
classes that you've seen in an earlier example — the
toBinaryString()
method that creates a
string representation of a binary integer. Here's the code:
import static java.lang.Long.*;
public class TryBitMethods {
public static void main(String[] args) {
long number = 0xF000_0000_0000_000FL;
System.out.println("number:\n" + toBinaryString(number));
long result = rotateLeft(number,2);
System.out.println(
"number rotated left 2 bits:\n" +
toBinaryString(result));
result = rotateRight(number, 3);
System.out.println(
"number rotated right 3 bits:\n" +
toBinaryString(result));