Technical Article

HexToINT

,

An optimized function for converting a HEX string into a INT. Built for being faster then other HexToDec converters.
Slightly slower then HexToSMALLINT.
If there is any faster function to do this conversion, I am intrested of using it instead.

/*
Input has to be a Valid Hexadecimal number. Example 4F or 04F or 004F. 
7FFFFFFF is the maximum value and it gives 2147483647 (Max INT)

Hans Lindgren
*/CREATE FUNCTION dbo.HexToINT 
(
@Value VARCHAR(8)
)
RETURNS INT
AS
BEGIN

SET @Value =  REVERSE( RIGHT( UPPER( '0000000' + @Value ) , 8 ) )

RETURN (
                (CHARINDEX( SUBSTRING( @Value , 1 , 1 ) , '0123456789ABCDEF' , 1 ) - 1 ) +
      16*       (CHARINDEX( SUBSTRING( @Value , 2 , 1 ) , '0123456789ABCDEF' , 1 ) - 1 ) +
      256*      (CHARINDEX( SUBSTRING( @Value , 3 , 1 ) , '0123456789ABCDEF' , 1 ) - 1 ) +
      4096*     (CHARINDEX( SUBSTRING( @Value , 4 , 1 ) , '0123456789ABCDEF' , 1 ) - 1 ) +
      65536*    (CHARINDEX( SUBSTRING( @Value , 5 , 1 ) , '0123456789ABCDEF' , 1 ) - 1 ) +
      1048576*  (CHARINDEX( SUBSTRING( @Value , 6 , 1 ) , '0123456789ABCDEF' , 1 ) - 1 ) +
      16777216* (CHARINDEX( SUBSTRING( @Value , 7 , 1 ) , '0123456789ABCDEF' , 1 ) - 1 ) +
      268435456*(CHARINDEX( SUBSTRING( @Value , 8 , 1 ) , '0123456789ABCDEF' , 1 ) - 1 )
)
END
GO


SELECT 
dbo.HexToINT('0ABCDEF') , 
dbo.HexToINT('01234567') , 
dbo.HexToINT('0FFF') , 
dbo.HexToINT('0')    AS MinValue, 
dbo.HexToINT('7FFFFFFF') AS MaxValue

Rate

You rated this post out of 5. Change rating

Share

Share

Rate

You rated this post out of 5. Change rating