How to count number of ones and zeros in a binary number?
Show older comments
I am having some set of binary numbers. I need to count the number of ones and zeros in each binary number. If a binary number has even number of ones then the output has to be '1' or it has to be '0'. Thank you in advance.
Example:
A=1100
B=0100
output of A =1
output of B = 0
Accepted Answer
More Answers (1)
% if you use char to represent binary numbers
A='1100';
mod(sum(A=='1'), 2) == 0
% if you use double to represent binaray numbers, you can do the conversion
% first
A = 1100;
A = num2str(A)
mod(sum(A=='1'), 2) == 0
4 Comments
Davide Masiello
on 29 Nov 2022
Edited: Davide Masiello
on 29 Nov 2022
Not sure you can convert from double to binary (char array) for any given number.
A = 0100;
A = num2str(A)
Or am I missing something?
To count number of 1, it is perfectly fine.
If you do need to get 0100, you have to specify the number of digits and leading 0s using sprintf:
A = 0100;
A = sprintf('%04d', A)
Davide Masiello
on 29 Nov 2022
Good point.
ASHA PON
on 29 Nov 2022
Categories
Find more on Data Type Conversion in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!