How to count number of ones and zeros in a binary number?
    30 Ansichten (letzte 30 Tage)
  
       Ältere Kommentare anzeigen
    
    ASHA PON
 am 29 Nov. 2022
  
    
    
    
    
    Kommentiert: ASHA PON
 am 29 Nov. 2022
            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
0 Kommentare
Akzeptierte Antwort
  Davide Masiello
      
 am 29 Nov. 2022
        
      Bearbeitet: Davide Masiello
      
 am 29 Nov. 2022
  
      I will assume that your binary numbers are stored as a character array, which is how Matlab normally works, e.g.
A = dec2bin(20)
B = dec2bin(21)
Now in the example above, A has an even and B has an odd number of ones respectively.
your desired output can be easily obtained with
1-mod(nnz(A=='1'),2)
1-mod(nnz(B=='1'),2)
3 Kommentare
  Davide Masiello
      
 am 29 Nov. 2022
				A= [1110, 0111, 0110, 1111];
B = 1-mod(sum(num2str(A') == '1',2),2)
Weitere Antworten (1)
  Chunru
      
      
 am 29 Nov. 2022
        % 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 Kommentare
Siehe auch
Kategorien
				Mehr zu Data Type Conversion finden Sie in Help Center und File Exchange
			
	Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!