Bit Manipulation Operation

From Java Example Source Code

Jump to: navigation, search

Contents

[edit] Overview - Bit Manipulation Operation

This Java example program shows how to operate bit.

[edit] Java Source Code

  • Package: example.bitset
  • File: Bits.java
  1. package example.bitset;
  2.  
  3. public class Bits {
  4.     public static void main(String args[]) {
  5. 	int n = 170; // 10101010
  6. 	System.out.println("Value in binary: 10101010");
  7.  
  8. 	System.out.println("Number of one bits: " + Integer.bitCount(n));
  9.  
  10. 	System.out.println("Highest one bit: " + Integer.highestOneBit(n));
  11.  
  12. 	System.out.println("Lowest one bit: " + Integer.lowestOneBit(n));
  13.  
  14. 	System.out.println("Number of leading zeros : " + Integer.numberOfLeadingZeros(n));
  15.  
  16. 	System.out.println("Number of trailing zeros : " + Integer.numberOfTrailingZeros(n));
  17.  
  18. 	System.out.println("\nBeginning with the value 1, " + "rotate left 16 times.");
  19. 	n = 1;
  20. 	for (int i = 0; i < 16; i++) {
  21. 	    n = Integer.rotateLeft(n, 1);
  22. 	    System.out.println(n);
  23. 	}
  24.     }
  25. }

[edit] What Result You Can Get

Run the program, you will get:

Value in binary: 10101010
Number of one bits: 4
Highest one bit: 128
Lowest one bit: 2
Number of leading zeros : 24
Number of trailing zeros : 1

Beginning with the value 1, rotate left 16 times.
2
4
8
16
32
64
128
256
512
1024
2048
4096
8192
16384
32768
65536

[edit] Required External Libraries and/or Files for this Java Example

Need nothing.


[edit] How to Run this Java Example Program

We recommend running this Java example program with Eclipse.

For assistance in working with Eclipse, please see How to Run Java Program with Eclipse.

It's fairly easy.



[edit] Question & Answer

Any question?

Click edit and post your question or answer here.


Personal tools