Back to Programming

Description

The program is written here to convert an octal number into its equivalent hexadecimal 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 hexadecimal.

For example, if an octal number is${\left(57\right)}_{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:

${8}^{1}$ + 7×${8}^{0}$

= 40 + 7

${\left(47\right)}_{10}$

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

The hexadecimal equivalent is ${\left(2F\right)}_{16}$

Algorithm

INPUT: An octal number

PROCESS:

Step 1: [Taking the input]

Step 2: [Converting the octal number to hexadecimal]

Set d<-0

Set p<-1

While n>0 repeat

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

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

[Increasing the power]

Set p<-p×8

Set n<-n/10

[End of ‘while’ loop]

Set p<-0

While d>0 repeat

Set r<-d mod 16

If r≤9 then

Set hex[p]<-character of (r+48)

Set p<-p+1

else if r=10 then

Set hex[p]<-'A'

Set p<-p+1

else if r=11 then

Set hex[p]<-'B'

Set p<-p+1

else if r=12 then

Set hex[p]<-'C'

Set p<-p+1

else if r=13 then

Set hex[p]<-'D'

Set p<-p+1

else if r=14 then

Set hex[p]<-'E'

Set p<-p+1

else if r=15 then

Set hex[p]<-'F'

Set p<-p+1

[End of ‘if-else if’]

Set d<-d/16

[End of ‘while’ loop]

Reverse the string stored in ‘hex’

Print the string stored in ‘hex’

Step 3: Stop.

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;

}

p=0;

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

{

r=d%16;

if(r<=9)

hex[p++]=(char)(r+48);

else if(r==10)

hex[p++]='A';

else if(r==11)

hex[p++]='B';

else if(r==12)

hex[p++]='C';

else if(r==13)

hex[p++]='D';

else if(r==14)

hex[p++]='E';

else if(r==15)

hex[p++]='F';

d=d/16;

}

The time complexity of this program 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 of this program is O(1) as it requires a constant number of memory spaces to execute for any given input.