二进制转十进制整数及浮点数lua实现

local function BinIntToHexInt(b1,b2,b3,b4)  –二进制转十进制整数

    local x = 0

    x = x*0x100 + b4

    x = x*0x100 + b3

    x = x*0x100 + b2

    x = x*0x100 + b1

    return x

end

local function BinFloatToHexFloat(b1, b2, b3, b4)   –二进制转十进制浮点数(传入参数从低到高位的四个字节)

    local sign = b4 > 0x7F  –符号位

    local expo = (b4 % 0x80) * 0x02 + math.floor(b3 / 0x80)  –整数部分

    local mant =  ((b3%0x80)*0x100+b2)*0x100+b1 –小数部分

    if sign then

        sign = -1

    else

        sign = 1

    end

    local n

    if mant == 0 and expo == 0 then

        n = sign * 0.0

    elseif expo == 0xFF then

        if mant == 0 then

            n = sign * math.huge

        else

            n = 0.0/0.0

        end

    else

        if (expo>0) and (expo<0xFF) then

            n = sign * math.ldexp(1.0 + mant / 8388608, expo – 0x7F)

        else

            n = sign * math.ldexp(0.0 + mant / 8388608, – 0x7E)

        end

    end

    return n

end

    原文作者:进制转换
    原文地址: https://blog.csdn.net/LMLBY/article/details/52998248
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞