Plugwise Float calculation in vbscript

Plugwise Forum about Plugwise devices and the Source software.
Post Reply
richard naninck
Member
Member
Posts: 123
Joined: Sun Nov 21, 2010 9:53 pm

Plugwise Float calculation in vbscript

Post by richard naninck »

Another one of my creations needed for Plugwise. VBScript doesn't have a native float conversion so here goes. It works but might be awfull to some of you but if someone needs this done in vbscript; here it is. And if somebody (like last time) already did this and even did it better, please post it here so I can benifit from it.

Code: Select all

'Label    HexValue    FloatValue
'GainA:   3F802571 -  1.00114262104
'GainB:   B5E5DEDB -  -1.712668904474E-6
'OffTot:  3D014486 -  0.031559489667
'OffRuis: 00000000 -  5.877471754111E-39

MsgBox HexToFloat("B5E5DEDB")

Function HexToFloat(Data)
Dim intBytes(4)
Dim intExp
Dim intDec
Dim fltVal
Dim nit

	For nit = 0 To 3
		intBytes(nit) = CLng("&H" & Mid(Data, (nit * 2) + 1, 2))
	Next
	
	'S Exp      Mantissa
	'x xxxxxxxx xxxxxxxxxxxxxxxxxxxxxxx
	'Low 7 bits of intBytes(0) shifted 1 bit left + 8th bit of intBytes(1) shifted 7 bits right
	intExp = ((intBytes(0) And 127) * 2^1)  + ((intBytes(1) And 128) / 2^7) - 127 
	intDec = Round(((((intBytes(1) And 127) * 2^16) + (intBytes(2) * 2^8) + intBytes(3)) / 2^23), 12) + 1
	fltVal = intDec * 2^intExp
	
	If (intBytes(0) And 128) = 128 Then
		fltVal = fltVal * -1
	End If
	
	HexToFloat = fltVal
End Function
Or if you like it dirty

Code: Select all

MsgBox HexToFloat("3F802571")

Function HexToFloat(Data)
Dim fltVal

	fltVal = (Round(((CLng("&H" & Data) And 8388607) / 2^23), 12) + 1) * (2^(((CLng("&H" & Left(Data, 6)) And 8355840) / 2^15) - 127))
	
	If (CLng("&H" & Left(Data, 2)) And 128) = 128 Then
		fltVal = fltVal * -1
	End If
	
	HexToFloat = fltVal
End Function
Post Reply

Return to “Plugwise Forum”