Number System Binary to Octal Conversion
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
Related post
- Decimal to binary using arithmetic operator
- Binary to decimal using arithmetic operator
- Decimal to 8 bit binary using arithmetic operator
- Decimal to binary using bitwise right-shift operator
- Binary to Decimal using bitwise right-shift operator
- Decimal to binary using bitwise left-shift operator
- Binary to Decimal using bitwise left-shift operator
- Octal to Binary number system conversion
- Hexadecimal to Binary number system conversion
- Binary to Hexadecimal number system conversion
Comments
Post a Comment