how to convert decimal to binary in c code example

Example 1: convert decimal to binary in c++

// C++ program to convert a decimal 
// number to binary number 
  
#include <iostream> 
using namespace std; 
  
// function to convert decimal to binary 
void decToBinary(int n) 
{ 
    // array to store binary number 
    int binaryNum[32]; 
  
    // counter for binary array 
    int i = 0; 
    while (n > 0) { 
  
        // storing remainder in binary array 
        binaryNum[i] = n % 2; 
        n = n / 2; 
        i++; 
    } 
  
    // printing binary array in reverse order 
    for (int j = i - 1; j >= 0; j--) 
        cout << binaryNum[j]; 
} 
  
// Driver program to test above function 
int main() 
{ 
    int n = 17; 
    decToBinary(n); 
    return 0; 
}

Example 2: binary to decimal in c

#include <math.h>
#include <stdio.h>
int convert(long long n);
int main() {
    long long n;
    printf("Enter a binary number: ");
    scanf("%lld", &n);
    printf("%lld in binary = %d in decimal", n, convert(n));
    return 0;
}

int convert(long long n) {
    int dec = 0, i = 0, rem;
    while (n != 0) {
        rem = n % 10;
        n /= 10;
        dec += rem * pow(2, i);
        ++i;
    }
    return dec;
}

Example 3: c program from decimal to binary

#include <stdio.h>
#include <math.h>
#include <stdlib.h>

#define D 10

int main()
{
	int i, n, k, vet[D];
   
	printf("FROM DECIMALS TO BINARIES\nEnter decimal: ");
	scanf("%d", &n);
   
	k = 0;
   
	while (n != 0)
	{
		if ((n % 2) == 1) 
			vet[k] = 1;
		else
			vet[k] = 0;
          
		n /= 2;
       
		k++;
	}
	
	printf("Transformed into binary: ");
    
	for(i = k - 1; i >= 0; i --)
		printf("%d", vet[i]);
		
	printf("\n\n");
    
	system("pause");
}

Tags:

C Example