Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting Hex to Float SQL

I am trying to find a way of converting HEX to a float in SQL Server.

An example value is 0x42c80000 which corresponds to 100.00.

It is easy to convert this Hex value to an Int using CONVERT but I can not find the float conversion equivalent.

like image 538
user1781272 Avatar asked May 30 '16 10:05

user1781272


1 Answers

DECLARE @BinaryFloat AS VARBINARY(4); 
SET @BinaryFloat = CONVERT(VARBINARY, '0x42c80000',1);

SELECT SIGN(CAST(@BinaryFloat AS INT))
  * (1.0 + (CAST(@BinaryFloat AS INT) &  0x007FFFFF) * POWER(CAST(2 AS REAL), -23))
  * POWER(CAST(2 AS REAL), (CAST(@BinaryFloat AS INT) & 0x7f800000) / 0x00800000 - 127)

Wish I could claim credit, but alas: http://multikoder.blogspot.com.au/2013/03/converting-varbinary-to-float-in-t-sql.html

Also, interesting blog https://blogs.msdn.microsoft.com/psssql/2010/11/01/how-it-works-sql-parsing-of-numbers-numeric-and-float-conversions/

like image 166
Liesel Avatar answered Nov 20 '22 08:11

Liesel