I'm new to java and am wondering if there is any way to count the actual number of ones and zeros in the binary of a single int. For example, I would try and find out the number of 1's and zero's in the binary 32 bit binary of int 6?
Asked
Active
Viewed 3,015 times
3
-
Do it the same way you would in any other language you know and wrap the logic in a `main()` in a class. – noMAD Sep 23 '14 at 20:59
-
2See http://stackoverflow.com/a/5263199/3802841 to see how an int can be formatted as a string. Count either the '0's or the '1' and substract the count from the length of the string. – Markus Patt Sep 23 '14 at 21:02
3 Answers
7
Using Integer.bitcount(int)
:
int ones = Integer.bitCount(n);
int zeros = Integer.bitCount(~n) - Integer.numberOfLeadingZeros(n);

Jean Logeart
- 52,687
- 11
- 83
- 118
-
-
Awesome. Who would have thought they'd already implemented this? http://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html#bitCount(int) – StriplingWarrior Sep 23 '14 at 21:06
-
-
@xgeorgekx: You're going to downvote all the answers but yours? Really? – StriplingWarrior Sep 23 '14 at 21:08
-
-
I have implemented this and for an n value of 36 Integer.bitCount(~n) returns 30 somehow... Does it flip all of the bits that an integer could contain o.O? – Blake Yarbrough Sep 23 '14 at 21:13
-
Well, the question is: "Is there any way to count the actual number of ones and zeros in the binary of a single int". Yes there is using this method. What is there to explain? – Jean Logeart Sep 23 '14 at 21:14
-
@LanguidSquid Yes, I edited to avoid having ``zeros = 32 - ones`` – Jean Logeart Sep 23 '14 at 21:14
-
That's neat! Thanks, I didn't know about that utility on Integer – Blake Yarbrough Sep 23 '14 at 21:16
2
Luckily, java has a built in method: Integer.toBinaryString() This takes an integer value, converts it to binary, then returns it as a String.
Or you could brush up on your java skills and create your own method to do it.

DJ Fresh
- 38
- 4
1
Since you provide no code i will give some guildines on how you can do it.
- Get the binary represesantation of your
int
by calling this methodInteger.toBinaryString(x);
- The previous method will return only the nessecery bits of the number for example in the case of
6
it will return110
. But you need a 32 bit representation of 6 so you have to add the extra zeros in front of the result returned from that method. - create 2 counter variables. One for ones and one for zeros.
- loop through the characters of your
String
and when achar == 0
increment the zeros counter. Whenchar == 1
increment the ones counter.
Hope this helps

gkrls
- 2,618
- 2
- 15
- 29
-
Why convert to ``String`` while the bits are *right there*, inside the ``int``? – Jean Logeart Sep 23 '14 at 21:16