Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- function hexToDec(num)
- if type(num)=="number" then
- error("String expected, got number.", 1)
- end
- local K=string.len(num)
- local N=K-1
- local Z
- local chars={}
- for n in num:gmatch("[%w+]") do
- table.insert(chars, n)
- end
- for key,v in ipairs(chars) do
- if v=="A" then
- chars[key]=tonumber(10)
- elseif v=="B" then
- chars[key]=tonumber(11)
- elseif v=="C" then
- chars[key]=tonumber(12)
- elseif v=="D" then
- chars[key]=tonumber(13)
- elseif v=="E" then
- chars[key]=tonumber(14)
- elseif v=="F" then
- chars[key]=tonumber(15)
- end
- end
- if K==4 then
- Z=(chars[1]*16^N)+(chars[2]*16^N-1)+(chars[3]*16^N-2)+chars[4]
- elseif K==3 then
- Z=(chars[1]*16^N)+(chars[2]*16^N-1)+chars[3]
- elseif K==2 then
- Z=(chars[1]*16^N)+chars[2]
- elseif K>4 then
- error("attempt to convert more than four numbers", 1)
- elseif K<2 then
- error("attempt to convert one number", 1)
- end
- return Z
- end
- print(hexToDec("5CE"))
Advertisement
Add Comment
Please, Sign In to add comment