如何在 lua 中将十六进制数转换为十六进制转义序列(即 \x 等价物)

How convert Hex number to Hex escaped Sequence(i.e. \x equivalent) in a lua

在各种语言中,十六进制值通过使用 \x 转义序列在字符串文字中显示为 \xhh 值

I using encrypting library in lua and hex ouptut is like:

e6dd6bf41a97b89980b2bc2e838bd1bb746b83139b4c1e7c73bdedcc18a01ec24e26703a60cc19d29750c22084470da889e67375afcd9b12595748f6b6ce2d7b436d56ab84e70c819ef52b1edf63148b0ee2cce672ff4d57115c7b51abaaf8a7

but in python library output is:

\xe6\xddk\xf4\x1a\x97\xb8\x99\x80\xb2\xbc.\x83\x8b\xd1\xbbtk\x83\x13\x9bL\x1e|s\xbd\xed\xcc\x18\xa0\x1e\xc2N&p:`\xcc\x19\xd2\x97P\xc2 \x84G\r\xa8\x89\xe6su\xaf\xcd\x9b\x12YWH\xf6\xb6\xce-{CmV\xab\x84\xe7\x0c\x81\x9e\xf5+\x1e\xdfc\x14\x8b\x0e\xe2\xcc\xe6r\xffMW\x11\{Q\xab\xaa\xf8\xa7

如何将十六进制数字转换为十六进制转义序列?

这是一个示例代码,有些字符可能会掉下来,但要点是这样的:

local s= [[e6dd6bf41a97b89980b2bc2e838bd1bb746b83139b4c1e7c73bdedcc18a01ec24e26703a60cc19d29750c22084470da889e67375afcd9b12595748f6b6ce2d7b436d56ab84e70c819ef52b1edf63148b0ee2cce672ff4d57115c7b51abaaf8a7]]

function escape (s)
      return string.gsub(s, '..', function (c)
            local ch = tonumber(c,16)                
            if ch==10 then return '\n' 
            elseif ch==13  then return '\r' -- 9 and \t ?
            elseif ch==92  then return '\\'
            elseif 0x1F<ch and ch<0x7f then return string.char(ch)
            else  return string.format("\x%s", c)
            end
          end)
 end
 
 print (escape (s) )

也许有更优雅的定义异常字符的解决方案。