Number System Binary to Octal Conversion

It is a C program which executes number system conversion from binary to octal numbers.


binary to octal

Binary to Octal - algorithm

          set octal []          

          Read  binary_bits form user                  
          reverse(binary_bits)
     
          while not EOF(binary_bits)
             
             read 3-bits from binary_bits
             convert 3-bits to decimal
             append decimal to octal             

          end    
         
         print reverse(octal)      
   

Binary to Octal conversion example

    
       The given binary number is 01101010010 and 
           converts it into octal number

         binary = 01101010010,  octal = ?, 
            
         split binary 3 bits group from right to left direction and
            carried out binary to decimal conversion on each 3 bits group  
                

       binary =   01 | 101 | 010 | 010
       octal =     1   5      2     2

      if binary = 01101010010 and equivalent octal = 1522
 
  

Binary to Octal - C programming code

The C program converts binary number to binary number. The program reads binary numbers from user as input and executes conversion process and returns octal number as result.
 

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

int bin2dec(char *bits,int start,int len) {
    
    int decval=0; char bit;
    int end = start + len-1;   
    for(int n=0;n<len;n++) 
     {  
       bit = bits[end-n] =='1' ? 1 : 0;   
       if ( bit==1)
       decval+= pow(2,n);             
     } 
  return decval;  
}


int main ()
{

   char octdigits[] = {'0','1','2','3','4','5',
                 '6','7'};
      
   char bits[16]; int len =0;
   char oct[5]; int k=0;
   int obs=3;
   
   printf("\n Binary to octal Conversion");
   
   printf("\n Enter Binary bits :") ;
   scanf("%s",&bits);

   len = strlen(bits);
   int startb=len;  
   
    while (startb>0) {
 
   startb -=obs; 
   if ( startb < 0  ) {
       startb +=obs;
          obs = startb;    
    startb -=obs; 
   }       
   
   int decval = bin2dec(bits,startb,obs);   
   //printf ("\n%d \t %d \t %d %c",startb,hbs,decval,hexc[decval]);
   
   oct[k++]= octdigits[decval];       
 }
    oct[k]='\0';
   
   printf("Octal value is :%s",strrev(oct));   
   
   return 0;
}
 

Binary to Octal Conversion - C program Output

 
 Binary to octal Conversion

 Enter Binary bits :01001101

 Octal value is :115






Download c program source code

Comments

Popular posts from this blog

Convert Octal to Binary

Hexadecimal to Binary Conversion

C program Simple Interest and Compound Interest