簡體   English   中英

在Lua中將十六進制轉換為十進制保持小數部分

[英]Convert hex to decimal keeping fractional part in Lua

Lua的tonumber函數很好,但只能轉換無符號整數,除非它們是10的基數。我有一種情況,我有像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

如果有的話,我會對這個更好的解決方案感興趣。

這是一個更簡單的解決方案:

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

如果你的Lua是用C99編譯器(或者更早的gcc)編譯的,那么......

~ e$ lua
Lua 5.1.4  Copyright (C) 1994-2008 Lua.org, PUC-Rio
> return tonumber"0x01.4C"
1.296875

將“十六”點向右移動兩個位置,轉換為十進制,然后除以256。

014C  ==>  332 / 256 = 1.296875

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM