'BYTE-FLOATS
============
'http://en.wikipedia.org/wiki/Minifloat
'related: IEE 754
'http://en.wikipedia.org/wiki/Single-precision_floating-point_format
'http://en.wikipedia.org/wiki/Half-precision_floating-point_format
sub FloatToByteFloat(sys pf,ph,n)
=================================
{
'USE OF REGISTERS:
'edx sign transform
'eax exponent transform
'ecx significand transform
'esi source pointer
'edi dest pointer
'
mov esi,pf
mov edi,ph
(
dec dword n
jl exit
mov ecx,[esi]
mov edx,ecx
mov eax,ecx
and edx,0x80000000 'mask sign bit
shr ecx,0x14 'reduce significand 23 bits to 3 bits 20==(23-3)
shr edx,0x18 'shove sign bit down 24
shr eax,0x17 'shove exponent down 23
and ecx,0x07 'mask significand 3 bits
and eax,0x0f 'mask exponent 4 bits
sub eax,0x78 'adjust exponent bias -120 == (7-127)
shl eax,0x03 'place exponent 3 bits up
or eax,ecx
or eax,edx
mov [edi],al
add esi,4
inc edi
repeat
)
}
sub ByteFloatToFloat(sys ph,pf,n)
=================================
{
'USE OF REGISTERS:
'edx sign transform
'eax exponent transform
'ecx significand transform
'esi source pointer
'edi dest pointer
'
mov esi,ph
mov edi,pf
(
dec dword n
jl exit
mov cl,[esi]
mov edx,ecx
mov eax,ecx
and edx,0x80 'mask sign bit
shl ecx,0x14 'expand significand 3 bits to 23bits (23-3)
shl edx,0x18 'shove sign bit up 24
shr eax,0x03 'shove exponent down 3
and ecx,0x7fffff 'mask 23 bit significand
and eax,0x0f 'mask exponent 4 bits
add eax,0x78 'adjust exponent bias 120 == (127-7)
shl eax,0x17 'place exponent 23 bits up
or eax,ecx
or eax,edx
mov [edi],eax
inc esi
add edi,4
repeat
)
}
string ShowFloatBits(float f)
=============================
{
string c, s=space 32
sys k,i
cast float k=f
for i = 1 to 32
if k and 0x80000000 then
c="1"
else
c="0"
end if
mid s,i,c
k=k << 1
next
return mid(s,1,1)+" "+mid(s,2,8)+" "+mid(s,10,8)+" "+mid(s,18,8)+" "+mid(s,26,7)+" "
}
string ShowByteFloatBits(sys h)
===============================
{
string c, s=space 8
sys k,i
k=h
for i = 1 to 8
if k and 0x80 then
c="1"
else
c="0"
end if
mid s,i,c
k=k << 1
next
return mid(s,1,1)+" "+mid(s,2,4)+" "+mid(s,6,3)+" "
}
'TESTS
'=====
'print ShowFloatBits 1.5
'print ShowFloatBits -2.5
% asz 2e7 'size of conversion arrays
byte bf[asz]
float sf[asz]
sf[1]=-1.5
print ShowFloatBits sf[1]
'print sf[1]
FloatToByteFloat @sf,@bf,1
print showByteFloatBits bf[1]
ByteFloatToFloat @bf,@sf,1
print showFloatBits sf[1]
print sf[1]
! GetTickCount lib "kernel32.dll" () as sys
'print "Start"
't1=GetTickCount
'FloatToHalfFloat @sf,@bf,asz
't2=GetTickCount
'print str( (1e6/asz) * (t2-t1),1) " nanoseconds per float conversion"