# Convert base-10 to base-16

How would I convert a base-10 number to it’s base-16 form, so when I use `tostring()`, it returns a hexadecimal number instead of a normal number?

2 Likes

String formatting is a good way to do this.

For example, converting 255 (decimal) into “FF” (hex), can be done like this

``````local hexString = string.format("%X", 255)
print(hexString)
--> FF
``````

There is a bit of ambiguity in your question - remember that numbers don’t inherently have a base, only representations of them. Here we are converting a Lua number, which I have expressed using the decimal number literal format (255), into a string of its hexademical representation (“FF”).

You can also directly declare a number literal in hexadecimal:

``````local twoFiftyFive = 0xFF
``````
10 Likes

i think this would work?

``````
function HexToNum(input:string)
hex = {A = 10, B = 11, C = 12, D = 13, E = 14, F = 15}
local t = {}
for i = 1, #input do
local letter = string.sub(input, i, i)
local v = nil
if tonumber(letter) == nil then -- string
if hex[string.upper(letter)] then
v = hex[string.upper(letter)]
end
elseif tonumber(letter) ~= nil then--number
v = letter
end
table.insert(t, v)
end
return t
end
``````

sorry

``````tonumber(`0x{hex}`, 16) -- 255
-- 2nd arg allows you convert between any base
-- tonumber is able to convert a string to a number
``````
1 Like