View Single Post
  #3   Report Post  
Posted to microsoft.public.excel.programming
Tom Ogilvy Tom Ogilvy is offline
external usenet poster
 
Posts: 6,953
Default faster way to convert hex to ieee754?

I don't know if it is faster, but it doesn't require direct use of copymemory

Type MyHex
Lng As Long
End Type
Type MySingle
sng As Single
End Type

Function Hex2Ieee754(b1, b2, b3, b4)
Dim h As MyHex
Dim s As MySingle
h.Lng = Val("&H" & b1 & b2 & b3 & b4 & "&")
LSet s = h
Hex2Ieee754 = s.sng
End Function

Sub Test()
Debug.Print Hex2Ieee754("40", "B8", "00", "00")
End Sub


It peforms the same - don't know if the same is correct or not in terms of
trying to achieve whatever you are trying to achieve.

--
Regards,
Tom Ogilvy


"Mark HOlcomb" wrote:

I am converting Hex to ieee754 floating point numbers using the following
attached code using VBA. Is this a 'fast' way to do this operation? My code
spends 90% of the time performing this operation. I'm hoping there is a
faster way. Any comments are apprectiate.

Thanks!
Mark


'To type cast in VB you need to use the API to copy the contents of one data
type into another....
'turns hex data into floating point ieee754 standard
Option Explicit
Private Declare Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory"
(Destination As Any, Source As Any, ByVal Length As Long)
Function Hex2Ieee754(b1, b2, b3, b4)

Dim bytArray(0 To 3) As Byte
Dim fResult As Single

' load your data (40 B8 00 00) into a byte array creates 5.75
' note the order is reversed

bytArray(3) = "&H" + b1
bytArray(2) = "&H" + b2
bytArray(1) = "&H" + b3
bytArray(0) = "&H" + b4

' copy into the float
CopyMemory fResult, bytArray(0), 4
' print the result (5.75)
'Debug.Print fResult
Hex2Ieee754 = fResult

End Function