If you need to convert a number from decimal to octal (base 8), two functions come to mind if you’re using MySQL. One function is specifically for doing octal conversions, the other is for doing conversions between different bases. These are as follows:
OCT()
- This function is used specifically for converting from decimal to octal.
CONV()
- This function has a more general purpose. It allows you to specify the base of the original number and the result. In other words, you can convert from any base, to any base (as long as each base is between 2 and 36).
More about these two functions below.
The OCT() Function
As mentioned, this function is specifically for converting from decimal to octal. Its syntax goes like this:
OCT(N)
Where N
is the decimal number you want to convert to octal.
Here’s an example:
SELECT OCT(8);
Result:
+--------+ | OCT(8) | +--------+ | 10 | +--------+
The result is 10
because that is the octal equivalent of 8 in the decimal system.
The CONV() Function
This is a more general purpose function that allows you to specify, not only the numbering system to convert to, but also the numbering system to convert from.
Syntax:
CONV(N,from_base,to_base)
Where N
is the number to convert, from_base
is the base to convert from, and to_base
is the base to convert to.
So we can rewrite the previous example to this:
SELECT CONV(8, 10, 8);
Result:
+----------------+ | CONV(8, 10, 8) | +----------------+ | 10 | +----------------+
And we get the same result because we convert the number from base 10 to base 8.
One benefit of the CONV()
function is that you can convert between other bases. For example, we could just as easily have converted from say, base 8 to base 16.
What is Octal?
Octal is a system of numerical notation that has 8 as a base. This is in contrast to decimal, which has 10 as a base.
In decimal, we count up to 9, then start again by adding a zero after the first digit (e.g. after 9 comes 10, which is 1 with a zero added to it).
In octal (base 8) however, we only count to 7 before starting again and adding a zero. So 10 in octal is the equivalent of 8 in decimal.
Here’s a table to demonstrate:
Decimal (Base 10) | Octal (Base 8) |
---|---|
1 | 1 |
2 | 2 |
3 | 3 |
4 | 4 |
5 | 5 |
6 | 6 |
7 | 7 |
8 | 10 |
9 | 11 |
10 | 12 |
11 | 13 |
12 | 14 |
13 | 15 |
14 | 16 |
15 | 17 |
16 | 20 |
17 | 21 |
18 | 22 |
19 | 23 |
20 | 24 |