I am trying to convert an hexadecimal string into decimal values, as follows:
Input : 24 character string
'1234567890abcdef12345678'
I need to extract the second to fourth characters, converting them into bits then separate them into two packs of 6 digits, and eventually convert them into decimal as follows:
'234'
bit conversion : 1000110100
separation into two packs of 6 digits : 001000, 110100
conversion into decimal : 8, 52
apply an operation : 8 * 2 - 128 = -112, 52 * 2 - 128 = -24
I have set up two functions to manage the conversion of each item (they also depend on another variable, which is a firmware, that has no influence in this case):
ALTER FUNCTION [getval1](@Firmware varchar(30), @RawData varchar(24))
RETURNS smallint
AS
BEGIN
DECLARE @val1 smallint;
IF @Firmware = 'v1'
OR @Firmware = 'v1.1'
OR @Firmware = 'v1.2'
OR @Firmware = 'v2'
BEGIN
SET @val1 = (CAST(fct.hexstrtovarbin(SUBSTRING(@RawData, 1, 4)) AS int) % 4096 / 64) * 2 - 128;
END
ELSE
BEGIN
IF @Firmware = 'v3'
OR @Firmware = 'v3.1'
OR @Firmware = 'v3.2'
OR @Firmware = 'v3.3'
BEGIN
SET @val1 = (CAST(fct.hexstrtovarbin(SUBSTRING(@RawData, 1, 4)) AS int) % 4096 / 64) * 2 - 128;
END
ELSE
BEGIN
SET @val1 = 0
END
END
RETURN @val1;
END;
ALTER FUNCTION [getval2](@Firmware varchar(30), @RawData varchar(24))
RETURNS smallint
AS
BEGIN
DECLARE @val2 smallint;
IF @Firmware = 'v1'
OR @Firmware = 'v1.1'
OR @Firmware = 'v1.2'
OR @Firmware = 'v2'
BEGIN
SET @val2 = (CAST(fct.hexstrtovarbin(SUBSTRING(@RawData, 1, 4)) AS int) % 64) * 2 - 128;
END
ELSE
BEGIN
IF @Firmware = 'v3'
OR @Firmware = 'v3.1'
OR @Firmware = 'v3.2'
OR @Firmware = 'v3.3'
BEGIN
SET @val2 = (CAST(fct.hexstrtovarbin(SUBSTRING(@RawData, 1, 4)) AS int) % 64) * 2 - 128;
END
ELSE
BEGIN
SET @val2 = 0;
END
END
RETURN @val2;
END;
However, if I run my functions with RawData = '5921000000b1212800b1219a', my outputs are :
- The first function seems to work perfectly well (output is -56).
- The second function outputs -126 instead of -62.
The strange thing to me is that if I just run the line:
SET @val2 = (CAST(fct.hexstrtovarbin(SUBSTRING(@RawData, 1, 4)) AS int) % 64)
I get the appropriate output (-62), but I don't get why the function returns a different output.
Any idea of what is happening here?
Many thanks!
EDIT : I forgot to mention that function fct.hexstrtovarbin returns a varbinary result from a string hexadecimal. The code is below:
CREATE FUNCTION fct.hexstrtovarbin(@input varchar(8000)) RETURNS varbinary(8000)
AS
BEGIN
DECLARE @Result AS varbinary(8000)
IF LEN(@input) % 2 <> 0
BEGIN
SET @Result = 0000000000;
END
ELSE
BEGIN
SET @Result = CONVERT(VARBINARY(8000), @input, 2);
END
RETURN @Result
END;
110100is 52 not 54.