C Program for Decimal to Binary Conversion?


Convert an integer from decimal number system (base-10) to binary number system (base-2). Size of an integer is assumed to be 32 bits, need you to divide the number by the base. It is used by the computer to change integer values to bytes that are a computer.

Input:10

Output:1010

Explanation

If the Decimal number is 10

  • When 10 is divided by 2 remainders is zero. Therefore, 0.

  • Divide 10 by 2. New number is 10/2 = 5.

  • when 5 is divided by 2 Remainder is 1. Therefore 1.

  • Divide 5 by 2. New number is 5/2 = 2.

  • when 2 is divided by 2 Remainder is zero. Therefore, 0.

  • Divide 2 by 2. New number is 2/2 = 1.

  • when 1 is divided by 2 Remainder is 1. Therefore, 1.

  • Divide 1 by 2. New number is 1/2 = 0.

  • number becomes = 0. Print the array in reverse order. The equivalent binary number is 1010.

Example

#include <iostream>
using namespace std;
int main() {
   long n, d, r, binary = 0;
   n=10;
   d = n;
   int temp = 1;
   while (n!=0) {
      r = n%2;
      n = n / 2;
      binary = binary + r*temp;
      temp = temp * 10;
   }
   printf("%ld", binary);
   return 0;
}

Updated on: 19-Aug-2019

900 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements