Decimal to Binary Conversion

The binary number consists of 0's and 1's such number system has only two distinct digits {0,1} is called base-2 number system or radix-2 number system. and The decimal number system consist of 0's to 9's has 10 distinct digits {0,1,2,3,4,5,6,7,8,9} is called base-10 number system or radix-10 number system.

The decimal to binary conversion or base-2 number to base-10 number conversion is carried out by c programming code. The decimal number is to convert is read from user during the program execution.

decimal to binary conversion

Decimal to Binary Conversion - Example

 
    Example decimal value =23
    converts it into equivalent binary bits =?
             
    The decimal-value divide by 2 returns a quotient and a reminder, 
            in which the quotient turns decimal-value to next round.                

     This process repeated until quotient becomes 0 or 1.
            
round Decimal divider quotient reminder
1 23 2 11 1
2 11 2 5 1
3 5 2 2 1
4 2 2 1 0
The result of binary bits collected from quotient and reminders. binary bits = final quotient bit + reminders bits The final round quotient=1 is added otherwise not and successive bits is collected from the reminder by bottom to top. binary bits = 10111


Decimal to binary conversion -algorithm

Declaration
Input Read integer decval
Output char bits
Loop decval not equal zero
reminder = decval module by 2
append reminder into bits
decval = decval divide by 2
n=n+1
End Loop
Output print, reverse(bits)

Decimal to Binary - C programming code

The C program code converts given decimal number into binary bits. The conversion carried out using arithmetic operation like modulus and division operation.

 

#include <stdio.h>
#include <string.h>

int main() {
  
 int decval=0; int reminder=0;
 int n=0,k=0,ntmp=0; 
 int bits[8];
 
 printf ("\n Decimal to Binary Conversion \n");
 printf ("\n Enter Decimal value : ");
 scanf("%d",&decval);
 
 while (decval !=1 && decval !=0) 
 {     
      reminder= decval %2;
      decval  = decval /2;       
      bits[n++] = reminder;
     
 }
 
 if ( decval==1 )
    bits[n++] = decval;
        
 printf ("\n Binary bits : "); 
 ntmp=n;
 for( k=0; k<ntmp; k++) {
    n--; 
    printf("%d",bits[n]);    
 }
    
 return 0;
}


Output

 
  Decimal to Binary conversion
     Enter Decimal value : 10

     Binary bits : 1010





Download source code

Comments

Popular posts from this blog

Hexadecimal to Binary Conversion

Convert Octal to Binary

Binary to Decimal conversion -Bitwise Left shift Operator