Thursday 27 March 2014

C Progamm to convert binary number into Octal System

/* To convert a number from binary to octal system,
no. of digit in binary no. should be multiple of three(3),
if not, then append 0's at front of the number,
e.g. 1001101 converted 001 001 101
then these group are converted to number as
    000        0
    001    1
    010    2
    011    3
    100    4
    101    5
    110    6
    111    7
*
/
#include<stdio.h>
#include<conio.h>
#include<math.h>

long binaryToOctal(int[],int);

void main(){
    int b[28],c,i;
    long dec;
    clrscr();
    //Enter binary no.
    printf("Enter a binary no.(max.27 digits longs):");
    c=0;
    while(c<28){
        b[c]=getch();
        if(b[c]==13) break;
        b[c]=b[c]-'0';
        if(b[c]==0||b[c]==1) {
        printf("%d",b[c]);
        c++;
        }
    }
    //Octal no.
    printf("\nOctal equivalent of binary no. ");
    for(i=0;i<c;i++)
        printf("%d",b[i]);
    dec=binaryToOctal(b,c); //Conversion
    printf(". is %ld",dec);//Result
    getch();
}

/*This function receives an array of binary digits
and convert them into a octal number */
/* Note: binary number's digit (e.g. 1001101) from right to left are stored in array from 0 to n-1*/
long binaryToOctal(int bn[],int len){
    int i,position;    //i for position of binary digit, position indicate position of octal-digit under conversion
    long oct,digit;    //oct for octal number, digit for octal-digit under conversion
    i=len-1,oct=0;
    position=0;
    while(i>=0)     {
        //Group of 3 binary digits are processed from left
        digit=bn[i--];       // 1st one from left
        if(i>=0) digit=2*bn[i--]+digit; // 2nd One from left(if exists)
        if(i>=0) digit=4*bn[i--]+digit; // 3rd One from left(if exists)
        oct=digit*pow(10.0,position)+oct; // Octal no.
        position++;                       // next digit to right
    }
    return oct; //return octal no.
}
//end of function
//End of Programm

No comments:

Post a Comment