Here are 3 ways to convert from decimal to hexadecimal in SQL Server.
Example 1 – The CONVERT() Function
First, we’ll use the CONVERT()
function. This allows you to convert between data types in SQL Server.
Here’s an example of using this function to convert a decimal value to hexadecimal:
SELECT CONVERT(VARBINARY(8), 64683) Result;
Result:
+------------+ | Result | |------------| | 0x0000FCAB | +------------+
In this case, we convert the decimal value 64683
to VARBINARY(8).
Example 2 – The CAST() Function
We can alternatively use the CAST()
function to do the same thing as the previous example:
SELECT CAST(64683 AS VARBINARY(8)) Result;
Result:
+------------+ | Result | |------------| | 0x0000FCAB | +------------+
Note that CAST()
and CONVERT()
use slightly different syntaxes. In the case of CAST()
the value to be cast comes first, whereas it’s the other way around with CONVERT()
.
Example 3 – The FORMAT() Function
We can also use the FORMAT()
function to format the decimal value as a hexadecimal string.
SELECT FORMAT(64683, 'X') Result;
Result:
+----------+ | Result | |----------| | FCAB | +----------+
The X
argument is what specifies that the resulting format should be hexadecimal.
You can also use a lowercase x
to specify that the result uses lowercase letters:
SELECT FORMAT(64683, 'x') Result;
Result:
+----------+ | Result | |----------| | fcab | +----------+
This function’s return value is nvarchar. This is different to the other two functions, which return the value as a binary constant (you can tell by the 0x
prefix).