lua-users home
lua-l archive

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


On Sat, 2010-01-09 at 02:04 +0800, KHMan wrote: 
> Norbert Kiesel wrote:
> > [snip]
> > function tohex(decimal)
> >    if type(decimal) == 'number' or #decimal < 15 then
> >       return ('%x'):format(decimal)
> >    end
> >    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 
> >       end
> >       hex = ('%x'):format(mod) .. hex
> >       decimal = div:match('0+(.+)')
> >    end
> > 
> >    return hex
> > end
> 
> Oh sorry, ha ha, I failed to see the nested loop. ;-)
> 
> It looks real slow... :-)
> 

Yeah, tabs went missing.  I include an untabbed version below (otherwise
unchanged).  Regarding the "real slow": it is guaranteed to decrease the
length of the decimal every round (due to the div:match() at the
bottom), so it's O(n^2).  Can you come up with something better?

</nk>
function tohex(decimal)
   if type(decimal) == 'number' or #decimal < 15 then
      return ('%x'):format(decimal)
   end
   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 
      end
      hex = ('%x'):format(mod) .. hex
      decimal = div:match('0+(.+)')
   end

   return hex
end