Categories
Programming SQL / Database

SQL convert integer to hexadecimal string

The following is a small SQL/Server function to convert an integer to a two digit hexadecimal string. I’m using it as part of a GPS mapping application to display the poll type from an Inmarsat D+ terminal.

CREATE FUNCTION ConvertToHex2
(
@pNumber int
)
RETURNS varchar(2)
AS
BEGIN
DECLARE @HexDigits varchar(16)
DECLARE @Digit1 int
DECLARE @Digit2 int
DECLARE @ResultVar varchar(2)

IF @pNumber IS NULL
SET @ResultVar = NULL
ELSE BEGIN
SET @HexDigits = ‘0123456789ABCDEF’
SET @Digit1 = @pNumber / 16 + 1
SET @Digit2 = @pNumber % 16 + 1
SET @ResultVar = SUBSTRING(@HexDigits, @Digit1, 1) + SUBSTRING(@HexDigits, @Digit2, 1)
END
RETURN @ResultVar
END