How to Convert a String to Hexadecimal in MySQL – HEX()

In MySQL, you can convert a string to its hexadecimal representation by using the HEX() function.

The HEX() function works on both strings and numbers, however, its handling of each of these is slightly different. When used to convert a number, it returns a hexadecimal string representation of the number treated as a longlong (BIGINT) number. But when converting a string, it returns a hexadecimal string representation of the string where each byte of each character is converted to two hexadecimal digits.

Syntax

Here’s how the syntax goes for converting a string to hex:

HEX(str)

Where str is the string you want to convert.

Example

Here’s an example:

SELECT HEX('Run');

Result:

+------------+
| HEX('Run') |
+------------+
| 52756E     |
+------------+

This converts the string Run into its hexadecimal equivalent (52756E).

Unhex a String

You can also “unhex” a hexadecimal value into its original string by using either the UNHEX() function, the X notation, or the 0x notation. For more information, see 3 Ways to Unhex a String in MySQL.