FOR FREE MATERIALS

Octal to Binary

Back to Programming

Description

The program is written here to convert an octal number into its equivalent binary number. The octal number is taken as input then it is first converted into its equivalent decimal number and then the decimal number is converted into its equivalent binary.

For example, if an octal number is (57)8

Now, the equivalent decimal number will be calculated by multiplying each digit of the octal number with the increasing power of 8 (the power will starts from 0 and will increase from right to left).

Therefore, the equivalent decimal number:

81 + 7×80

= 40 + 7

=(47)10

Now, this decimal number will be converted into its equivalent binary by dividing it with 2 until the quotient of the division becomes zero and then take the remainders in reversed order.

The binary equivalent is (101111)2

Algorithm

INPUT: An octal number

OUTPUT: Equivalent binary number

PROCESS:

Step 1: [Taking the input]

               Read n [an octal number]

Step 2: [Converting from octal to binary]

               Set d<-0

               Set p<-1

               Set i<-0

                While n>0 repeat

                              [Calculating the power of 8 and multiplied with the octal digit]

                              Set d<-d+(n mod 10)×p

                              [Increasing the power]

                              Set p<-p×8

                              Set n<-n/10

               [End of ‘while’ loop]

               [Converting from decimal to binary]

               While d>0 repeat

                              Set binary[i]<-character of (d mod 2+48)

                              Set d<-d/2

               [End of ‘while’ loop]

               Set binary[i]<-'\0’

               [printing the binary number]

               Reverse the string stored in the variable ‘binary’

               Print the value of the variable ‘binary’

Step 3: Stop.

Code

TIME COMPLEXITY:

while(n>0)-----------------------------------------O(k)

               {

                              //calculating the power of 8 and multiplied

                              //with the octal digit

                              d=d+(n%10)*p;

                              //increasing the power

                              p=p*8;

                              n=n/10;

               }

               //converting from decimal to binary

               while(d>0)----------------------------------------O(m)

               {

                              binary[i++]=(char)(d%2+48);

                              d=d/2;

               }

 

The time complexity of converting an octal number to binary is O(k+m) where ‘k’ is the number of digits of the octal number and ‘m’ is the number of digits of the decimal number.

SPACE COMPLEXITY:

The space complexity is O(1) as it requires a constant number of spaces to execute for any given input.