Converting integer value to a string
ascii, lua, string
Solution
- Use `local` whenever you are creating variables with similar names (for eg. `code` and `value` in your code).
- When you use `value = value / 254`, you need to take only the integer part of the division and not the entire number.
Therefore:
function encode(value)
local code = ''
while value % 254 ~= value do
code = code .. string.char( value % 254 )
value = math.floor( value / 254 )
end
code = code .. string.char( value )
return code
end
function decode(code)
local value = 0
code = code:reverse()
for i = 1, #code do
local c = code:sub( i, i )
value = value * 254 + c:byte()
end
return value
end
Problem
Below is code to encode an integer value into an ASCII string. It is written in Python, and works fine from my testings. ``` def encode(value): code = '' while value%254 != value: code = code + chr(value%254) value = value/254 code = code + chr(value) return code def decode(code): value = 0 length = len(code) for i in range(0, length): print code[i] value = value * 254 + ord(code[length-1-i]) return value code = encode(123456567) print code print decode(code) ``` However when I try the same implementation in Lua, the values encoded and decoded do not match up. Here is my Lua version: ``` function encode(value) code = '' while value%254 ~= value do code = code .. string.char(value%254) value = value/254 end code = code .. string.char(value) return code end function decode(code) value = 0 code = string.reverse(code) for i=1, #code do local c = code:sub(i,i) print(c) value = value*254 + string.byte(c) end return value end code = encode(2555456) print(decode(code)) ``` Please note that I am trying to using mod 254 so that I can used 255 as a delimiter.