if OBJECTPROPERTY( OBJECT_ID( 'dbo.BitsToFloat' ) , 'IsScalarFunction' ) is not null
drop function dbo.BitsToFloat
GO
create function dbo.BitsToFloat (
@IEEE64 binary(8),
@Start tinyint = 1,
@End tinyint = 64,
@Inverse bit = 0
)
-- Returns either sum of powers of 2 for the bits or inverse i.e., as 1/2 + 1/4 + 1/8...
returns float
as
begin
/********************************************************************************/
/* Created By : Umachandar Jayachandran (UC) */
/* Created On : 28 July 2002 */
/* Description : This function returns either sum of powers of 2 for the bits */
/* or inverse i.e., as 1/2 + 1/4 + 1/8... */
/* Please note that this counts bits from left to right for every*/
/* byte sequence. */
/********************************************************************************/
/* Resources : https://umachandar.com/resources.htm */
/********************************************************************************/
return (
select sum( b.Val * power( cast( 2. as float ),
case @Inverse when 0
then @End - b.Num
else (b.Num - @Start + 1) * -1
end ) )
from dbo.BytesToBits( @IEEE64, @Start, @End ) as b
)
end
go
-- Usage:
select cast( dbo.BitsToFloat( 0x3EB36946F40DE1F3 /* IEEE format */, 2, 12, default ) as int ) "Exp"
select 1. + cast( dbo.BitsToFloat( 0x3EB36946F40DE1F3 /* IEEE format */, 13, 64, 1 ) as float ) "Val"
/*
Exp
-----------
1003
Val
-----------------------------------------------------
1.2132024319999999
*/
-- Shows how to convert internal binary val to IEEE format
select cast( dbo.BitsToFloat( dbo.BinaryToIEEE64(0xF3E10DF44669B33E), 2, 12, default ) as int ) as "Exp",
cast( 1. + dbo.BitsToFloat( dbo.BinaryToIEEE64(0xF3E10DF44669B33E), 13, 64, 1 ) as float ) as "Val"
/*
Exp Val
----------- -----------------------------------------------------
1003 1.2132024319999999
*/
This page was last updated on May 01, 2006 04:28 PM.