MySQL HEX() Function
The MySQL HEX() function returns a string containing hexadecimal representation of decimal or string value.
For a string argument str, this function returns a hexadecimal string representation of str where each byte of each character in str is converted to two hexadecimal digits (For Multibyte characters become more than two digits). The inverse of this operation can be performed by using UNHEX() function.
For a numeric argument N, this function returns a hexadecimal string representation of the value of N. This is equivalent to using the CONV() function with CONV(N, 10, 16) syntax. The inverse of this operation can be performed by using the CONV() function with CONV(HEX(N), 16, 10) syntax.
Syntax
/* with string argument */ HEX(str) /* with numeric argument */ HEX(N)
Parameters
str |
Required. Specify the string to convert to a hexadecimal representation. |
N |
Required. Specify the number to convert to a hexadecimal representation. |
Return Value
Returns the hexadecimal representation of a decimal or string value.
Example 1:
The example below shows the usage of HEX() function.
mysql> SELECT X'78797A', HEX('xyz'), UNHEX(HEX('xyz')); Result: 'xyz', '78797A', 'xyz' mysql> SELECT X'53514C', HEX('SQL'), UNHEX(HEX('SQL')); Result: 'SQL', '53514C', 'SQL' mysql> SELECT HEX(255), CONV(HEX(255), 16, 10); Result: 'FF', '255' mysql> SELECT HEX(500), CONV(HEX(500), 16, 10); Result: '1F4', '500'
Example 2:
Consider a database table called Sample with the following records:
Data | x |
---|---|
Data 1 | 10 |
Data 2 | 20 |
Data 3 | 30 |
Data 4 | 40 |
Data 5 | 50 |
The statement given below can be used to get the hexadecimal representation of values of column x.
SELECT *, HEX(x) AS HEX_Value FROM Sample;
This will produce the result as shown below:
Data | x | HEX_Value |
---|---|---|
Data 1 | 10 | A |
Data 2 | 20 | 14 |
Data 3 | 30 | 1E |
Data 4 | 40 | 28 |
Data 5 | 50 | 32 |
❮ MySQL Functions