Tuesday 30 July 2019

2 Ways to Convert between Decimal and Hexadecimal in MySQL

This article presents two methods for converting a decimal number to its hexadecimal equivalent in MySQL.
More specifically, I present two functions that enable you to do this conversion. The two functions are as follows:
  • The HEX() function
  • The CONV() function
Below is an explanation of each function.

The HEX() Function

The HEX() function actually works on both numbers and strings. Here’s the syntax for using this function with numbers:
HEX(N)
Where N is the number you want to convert to hexadecimal.

Example

SELECT HEX(108);
Result:
+----------+
| HEX(108) |
+----------+
| 6C       |
+----------+
So 108 in decimal is 6C in hexadecimal. We can also get the same result by using the CONV() function.

The CONV() Function

The CONV() function has a more widespread use, in that it can be used to convert between any number of numeric systems (as long as they’re no lower than base 2 and no higher than base 36).
The syntax goes like this:
CONV(N,from_base,to_base)
Where N is the number you want to convert, from_base is the base you want to convert from, and to_base is the base you want to convert to.

Example

Therefore, we can rewrite the previous example to this:
SELECT CONV(108, 10, 16);
Result:
+-------------------+
| CONV(108, 10, 16) |
+-------------------+
| 6C                |
+-------------------+
So we can see by the code that we’re converting 108 from base 10 (decimal) to base 16 (hexadecimal).

0 comments:

Post a Comment