int bit operations
In this chapter you will learn:
- How to reverse and rotate the integer in binary format
- How to bit oriented operation on int type value
- How to get the leading and trailing zeros
Reverse and rotate the integer in binary format
static int reverse(int i)
reverses the bits.static int reverseBytes(int i)
reverses the bytes.static int rotateLeft(int i, int distance)
rotates the bits by distance to left.static int rotateRight(int i, int distance)
rotates the bits by distance to right.
The following code reverse decimal value 10 in binary format.
public class Main {
public static void main(String[] args) {
/* j a va 2 s . c om*/
System.out.println(Integer.reverse(10));
}
}
The output:
The following code rotates value 10 to left for distance of 2.
public class Main {
public static void main(String[] args) {
// j a v a 2s . c o m
System.out.println(Integer.rotateLeft(10,2));
}
}
The output:
Bit oriented operation
static int bitCount(int i)
counts the bitsstatic int highestOneBit(int i)
returns an int value with at most a single one-bit, in the position of the highest-order ("leftmost") one-bit.static int lowestOneBit(int i)
returns an int value with at most a single one-bit, in the position of the lowest-order ("rightmost") one-bit.
The following code does the bit oriented operation on value 10
.
public class Main {
public static void main(String[] args) {
//from j a va 2 s . c o m
System.out.println(Integer.bitCount(10));
System.out.println(Integer.highestOneBit(10));
System.out.println(Integer.lowestOneBit(10));
}
}
The output:
Get the leading and trailing zeros
static int numberOfLeadingZeros(int i)
returns the number of zero bits preceding the highest-order ("leftmost") one-bitstatic int numberOfTrailingZeros(int i)
returns the number of zero bits following the lowest-order ("rightmost") one-bit
public class Main {
public static void main(String[] args) {
//from j a v a 2 s . co m
System.out.println(Integer.numberOfLeadingZeros(10));
}
}
The output:
Next chapter...
What you will learn in the next chapter:
- What is Java long type
- How to mark an integer as long type
- Find out the max/min value and its size for long type
- How to create Long object
- How to get the sign of the long value
- How to get the number of zero bits preceding and following
- How to reverse and rotate a long value
Home » Java Tutorial » Primitive Data Types