lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


I'm trying to convert arbitrary long decimals (encoded as a string of
digits) to it's hex representation (i.e. a string of hexadecimal
digits).  For short decimals, format('%x') is the way to go.  That
looses out however for e.g. '5766297887677882160' because we loose
precision when it's internally converted to a (floating point) number:
it returns '50060160b0202000' instead of '50060160b0201f30'.

So please help me out.  Here is what I came up with, is that correct or
is there a better/faster way to do it (I know that BigNum can do it, but
this is not pure Lua).

function tohex(decimal)
   if type(decimal) == 'number' or #decimal < 15 then
      return ('%x'):format(decimal)
   local hex = ''
   while decimal do
      local div = ''
      local mod = 0
      for i = 1, #decimal do
mod = mod * 10 + tonumber(decimal:sub(i, i))
local f = math.floor(mod / 16)
mod = mod - f * 16
div = div .. f 
      hex = ('%x'):format(mod) .. hex
      decimal = div:match('0+(.+)')

   return hex