C decimal to binary code instances

  • 2020-04-02 02:21:30
  • OfStack

Using C language to achieve the decimal into binary, and the number of 1 statistics in the converted binary code.


#include <stdio.h>

int binaryNum[16];  //Store the converted binary code
int count=0;  //Counts the number of times a decimal integer is divided by 2
int oneCount=0;  //The number of 1's in the binary code

void main(){
  int num;
  printf(" Enter a decimal integer: ");
  scanf("%d",&num);	
	
  while( (num/2) != 1 ){  //The judgment condition is: the quotient after dividing by 2 does not equal 1
    binaryNum[count] = num%2;  //The remaining Numbers are stored in an array
    num /= 2;  //Num = num / 2; Proceed to the next round of judgment
    count++;  //This variable is used to specify array subscripts
  }
  binaryNum[count+1] = 1;  //After the last division, the quotient must be 1, so manually add a 1 at the end

  printf(" The binary value is: ");
  //Prints out the elements of the array in reverse order
  //Sizeof /sizeof = number of elements in the array
  for( int i=sizeof(binaryNum)/sizeof(int)-1; i>=0; i-- ){
    if( binaryNum[i] == 1)
      oneCount++;  //So once you have a 1, it adds up
    printf("%d",binaryNum[i]);
  }
  printf("n A total of %d a 1n",oneCount);
}


Related articles: