Log In  
Follow
vitoralmeidasilva

Here is a simple function to convert a number to its hexadecimal string representation:

function num2hex(number)
	local base = 16
	local result = {}
	local resultstr = ""

	local digits = "0123456789abcdef"
	local quotient = flr(number / base)
	local remainder = number % base

	add(result, sub(digits, remainder + 1, remainder + 1))

  while (quotient > 0) do
  	local old = quotient
  	quotient /= base
  	quotient = flr(quotient)
  	remainder = old % base

		 add(result, sub(digits, remainder + 1, remainder + 1))
  end

  for i = #result, 1, -1 do
  	resultstr = resultstr..result[i]
  end

  return resultstr
end

Usage:

	print(num2hex(255)) -- ff
	print(num2hex(10)) -- a
	print(num2hex(1050)) -- 41a
2
3 comments