
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Count Total Bits in a Number using Java
The total bits in a number can be counted by using its binary representation. An example of this is given as follows −
Number = 9 Binary representation = 1001 Total bits = 4
A program that demonstrates this is given as follows.
Example
public class Example { public static void main(String[] arg) { int num = 10; int n = num; int count = 0; while (num != 0) { count++; num >>= 1; } System.out.print("The total bits in " + n + " are " + count); } }
Output
The total bits in 10 are 4
Now let us understand the above program.
First, the number is defined. Then the total bits in the number are stored in count. This is done by using the right shift operator in a while loop. Finally, the total bits are displayed. The code snippet that demonstrates this is given as follows −
int num = 10; int n = num; int count = 0; while (num != 0) { count++; num >>= 1; } System.out.print("The total bits in " + n + " are " + count);
Advertisements