- 1

How to calculate the sum of binary code ?

Example: the binary code of number 9 is 1001. I want to calculate and get the result 2. 1+0+0+1 = 2. What should I do ?

11th Apr 2020, 4:36 AM
Socheat Sorng
Socheat Sorng - avatar
8 Answers
11th Apr 2020, 4:45 AM
Kiran Deep Naidu
Kiran Deep Naidu - avatar
+ 3
You can simply use the built-in function __builtin_popcount(). It returns number of set bits in binary representation of a number and that's what the sum of all 1's is.
12th Apr 2020, 10:09 PM
Hima
Hima - avatar
+ 2
Thanks Martin
12th Apr 2020, 1:01 PM
Kiran Deep Naidu
Kiran Deep Naidu - avatar
+ 1
Kiran Deep Naidu Thanks for your help.
11th Apr 2020, 4:51 AM
Socheat Sorng
Socheat Sorng - avatar
0
I hope this helps you😊😊
11th Apr 2020, 4:45 AM
Kiran Deep Naidu
Kiran Deep Naidu - avatar
0
Taylor, I have corrected the code as you said but I still wonder this gonna not be appropriate one because we need to apply the 2's complement for finding the binary of negative number.
12th Apr 2020, 7:39 AM
Kiran Deep Naidu
Kiran Deep Naidu - avatar