The program is written here to convert a hexadecimal number into its equivalent octal number. The hexadecimal number is first converted into its equivalent decimal number and then the decimal number is then converted into its equivalent octal.
For example, if a hexadecimal number is ()
Now, the equivalent decimal number will be calculated by multiplying each digit of the hexadecimal number with the increasing power of 16 (the power will starts from 0 and will increase from right to left).
Therefore, the equivalent decimal number:
A× + 2×
= 10× + 2×
= 160 + 2
=
Now, this decimal number will be converted into its equivalent octal by dividing it with 8 until the quotient of the division becomes zero and then take the remainders in reversed order.
Therefore, the octal number is
INPUT: A hexadecimal number
OUTPUT: Equivalent octal number
PROCESS:
Step 1: [Taking the input]
Read ‘hex’ [a variable to store hexadecimal number]
Step 2: [Converting hexadecimal number into octal]
Set d<-0
Set b<-1
Set p<-1
Set oct<-0
Set n<-length of the string stored in variable ‘hex’
For i=0 to n-1 repeat
If hex[i]≥'a' and hex[i]≤'z' then
Set hex[i]<-hex[i]-32
[End of ‘if’]
[End of ‘for’ loop]
[Converting hexadecimal number to decimal]
For i=n-1 to 0 step -1 repeat
[if the value is a numeric digit]
If hex[i]≥'0' and hex[i]≤'9' then
Set d<-d+(hex[i]-48)×b
Set b<-b×16
[End of ‘if’]
[If the value is greater equals to 10 and less equals to 15]
else if hex[i]≥'A' and hex[i]≤'F' then
Set d<-d+(hex[i]-55)×b
Set b<-b×16
[End of ‘else if’]
[End of ‘for’ loop]
[Converting from decimal to octal]
While d>0 repeat
Set oct<-oct+(d mod 8)×p
Set d<-d/8
Set p<-p×10
[End of ‘while’ loop]
[printing the octal number]
Print the value of the variable ‘oct’
Step 3: Stop.
//converting hexadecimal number
//to decimal
for(i=n-1;i>=0;i--)---------------------------------------O(n)
{
//if the value is a numeric digit
if(hex[i]>='0' && hex[i]<='9')-------------O(1)
{
d=d+(hex[i]-48)*b;
b=b*16;
}
//if the value is greater equals to 10 and
//less equals to 15
else if(hex[i]>='A' && hex[i]<='F')-------O(1)
{
d=d+(hex[i]-55)*b;
b=b*16;
}
}
//converting from decimal to octal
while(d>0)-----------------------------------------------O(m)
{
oct=oct+(d%8)*p;
d=d/8;
p=p*10;
}
//printing the octal number
printf("The octal number is: %d",oct);
The time complexity of this program is O(n+m) where ‘n’ is the number of digits of the hexadecimal number and ‘m’ is the number of digits of the decimal number.
The space complexity of this program is O(1) as the program needs a constant number of memory space to execute the program for any given input.