[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
**Subject**: **Re: IEEE-754 encode/decode**
**From**: KHMan <keinhong@...>
**Date**: Sun, 28 Mar 2010 13:43:15 +0800

Clark Snowdall wrote:

Hello all,
I'm a newbie here so be gentle ...
I need to convert back and forth between a string of bytes (4 bytes, 32-bits), and IEEE-754 floating point. Basically I need to read a byte stream from a network socket and convert those bytes to a number.
For example I need to convert:
x = string.char(0x42, 0x96, 0x00, 0x00)
to:
y = 74.0
And vice versa. I understand the IEEE-754 standard and if pressed could probably muddle through writing something from scratch. But as with any programmer, if someone's already done it or if it's already in the language somewhere, it would just be easier than reinventing the wheel.
Any ideas folks?

From ChunkSpy, has been casually tested with a few numbers...
function convert(x)
local sign = 1
local mantissa = string.byte(x, 3) % 128

` for i = 2, 1, -1 do mantissa = mantissa * 256 + string.byte(x,
``i) end
` if string.byte(x, 4) > 127 then sign = -1 end
local exponent = (string.byte(x, 4) % 128) * 2 +
math.floor(string.byte(x, 3) / 128)
if exponent == 0 then return 0 end
mantissa = (math.ldexp(mantissa, -23) + 1) * sign
return math.ldexp(mantissa, exponent - 127)
end

`To avoid any copyright ambiguity, I declare the above to be in
``public domain.
`
--
Cheers,
Kein-Hong Man (esq.)
Kuala Lumpur, Malaysia