• Subject: converting arbitrary long decimals to hex?
• From: Norbert Kiesel <nkiesel@...>
• Date: Fri, 08 Jan 2010 08:55:32 -0800

```Hi,

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'.

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)
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

</nk>

```

• Follow-Ups: