Lua - ‘String to Hex’ 和 ‘Hex to String’ 公式

我试图保留我遇到的各种 Lua 代码示例以供重用,其中 strtohex() 和 hextostr() 是其中一个示例,但我只能找到 strToHex() - 如下所示..

local s = "175"
local function strToHex(s)
  local bytes = {}
  for i=1,s:len()  do
    bytes[#bytes+1] = ('%2x'):format(s:byte(i,i))
  end
  return table.concat(bytes, ' ')
  --return table.concat(bytes, '')
end
print(strToHex(s))

有人有 hextostr() 的示例可以分享吗?

点赞
用户4984564
用户4984564
本地函数 `hexdecode`

返回 `hex` 使用 `gsub`  格式化为 `%x%x`,该函数内部回调使用 `string.char` 将返回值从十六进制转换为字符。

本地函数 `hexencode`

返回 `str` 使用 `gsub`,. 匹配任意单个字符,回调使用 `string.format` 将字符转换为十六进制格式并返回。

最后通过 `print` 打印 `hexencode` 格式化后的值传入 `hexdecode` 函数进行反向转换。

输出 `Hello, World!`,该字符串使用十六进制编码和解码两次。
2020-12-28 12:28:12