How to fast convert from Octal to Hexadecimal

21k Views Asked by At

There has been a similar question before: How to convert a hexadecimal number to an octal number?

But, in my case I need an Algorithm to directly convert a number from Octal to Hexadecimal and back without converting it to binary/decimal as an intermediate step. Is it possible?

3

There are 3 best solutions below

5
On BEST ANSWER

Use octal digits as hexadecimal ones and then just add the numbers you got with weights of $8^n$, working in hexadecimal.

For example: consider $a=347_8$. To get a hexadecimal representation without resorting to binary or decimal, you can use the fact that $8<16$, i.e. just take the digits as they are. Now you just do the computation:

$$\text{hex}(a)=7\cdot 8^0+4\cdot 8^1+3\cdot 8^2=7_{16}+20_{16}+\text{C}0_{16}=\text{E}7_{16}.$$

Keep in mind that you have to do the multiplication and addition in hexadecimal to fullfill your requirements to not leave hex/oct representation.

0
On

group the octal digits in groups of 4: $\{O_1,O_2,O_3,O_4\}$ prepending $0$ as needed

then the first hex digit is $O_1*2+\lfloor \frac{O_2}{4}\rfloor$

the second is $O_2*4+\lfloor \frac{O_3}{2}\rfloor \mod 16$

then the last digit is $O_3*8+O_4 \mod 16$

I make use of the fact that $8^4=16^3$ so each group of 4 octal digits maps 1-1 to 3 hex digits.

to use the example of $347_8$ from the other answers my digits are $\{0,3,4,7\}$

the first hex digit is $0*2+\lfloor \frac{3}{4}\rfloor=0$

the second is $3*4+\lfloor \frac{4}{2}\rfloor \mod 16=12+2=14=E_{16}$

the third digit is $4*8+7 \mod 16=32+7\mod16=7$

so the result is $\text{0E7}_{16}$

2
On

Using binary representation as an intermediate step really saves you a lot of computation. Consider $347_8$, you can convert it to binary just digit by digit. $$347_8 = 11\, 100\, 111_2$$ Now you regroup the bits into groups of $4$ and go the other way to hexadecimal. $$\rm 1110\,0111_2 = E7_{16}$$ No need to do any computation except from converting single digits at all.