Skip to content
Advertisement

SQL: Convert integer into formatted hex string

In PostgreSQL, let’s say I have the following table:

+-------+---------+
|       | someVal |
| myInt |         |
+-------+---------+
| 123   | a       |
+-------+---------+
| 456   | b       |
+-------+---------+
| 789   | c       |
+-------+---------+

I want to convert the myInt column into a formatted string that contains the hex representation of the integer in it and rename the column. So it would look something like the following:

+----------+---------+
|          | someVal |
| myHex    |         |
+----------+---------+
| hex: 7B  | a       |
+----------+---------+
| hex: 1C8 | b       |
+----------+---------+
| hex: 315 | c       |
+----------+---------+

What would the query look like to convert the integer?

Advertisement

Answer

Try the following in PostgreSQL.

select
   concat('hex: ', cast(to_hex(ms) as text)) as myHex,
   someVal
from yourTable
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement