下面是将整数值编码为ASCII字符串的代码.它是用 Python编写的,从我的测试中可以正常工作. def encode(value): code = '' while value%254 != value: code = code + chr(value%254) value = value/254 code = code + chr(va
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)
但是,当我在Lua中尝试相同的实现时,编码和解码的值不匹配.这是我的Lua版本:
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))
请注意,我正在尝试使用mod 254,以便我可以使用255作为分隔符.
>每当您创建具有相似名称的变量时(例如代码中的代码和值),请使用local.>使用value = value / 254时,只需要除法的整数部分而不是整数.
因此:
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