代码之家  ›  专栏  ›  技术社区  ›  Zack The Human Kunal

将十六进制转换为十进制,保留Lua中的小数部分

  •  4
  • Zack The Human Kunal  · 技术社区  · 16 年前

    01.4C 我想转换成十进制。

    我有一个糟糕的解决方案:

    function split(str, pat)
       local t = {} 
       local fpat = "(.-)" .. pat
       local last_end = 1
       local s, e, cap = str:find(fpat, 1)
       while s do
          if s ~= 1 or cap ~= "" then
            table.insert(t,cap)
          end
          last_end = e+1
          s, e, cap = str:find(fpat, last_end)
       end
       if last_end <= #str then
          cap = str:sub(last_end)
          table.insert(t, cap)
       end
       return t
    end
    -- taken from http://lua-users.org/wiki/SplitJoin
    
    function hex2dec(hexnum)
      local parts = split(hexnum, "[\.]")
      local sigpart = parts[1]
      local decpart = parts[2]
    
      sigpart = tonumber(sigpart, 16)
      decpart = tonumber(decpart, 16) / 256
    
      return sigpart + decpart
    end
    
    print(hex2dec("01.4C")) -- output: 1.296875
    

    3 回复  |  直到 16 年前
        1
  •  7
  •   Doug Currie    16 年前

    如果您的Lua是用C99编译器(或者更早的gcc)编译的,那么。。。

    ~ e$ lua
    Lua 5.1.4  Copyright (C) 1994-2008 Lua.org, PUC-Rio
    > return tonumber"0x01.4C"
    1.296875
    
        2
  •  9
  •   lhf    16 年前

    function hex2dec(hexnum)
            local a,b=string.match(hexnum,"(.*)%.(.*)$")
            local n=#b
            a=tonumber(a,16)
            b=tonumber(b,16)
            return a+b/(16^n)
    end
    
    print(hex2dec("01.4C")) -- output: 1.296875
    
        3
  •  4
  •   Robert Harvey    16 年前

    014C  ==>  332 / 256 = 1.296875