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

Time:02-27

In various languages, hex values shows as \xhh values in a string literal by using the \x escape sequence

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

how can i convert Hex number to Hex escaped sequence?

CodePudding user response:

Here is an example code, some characters may fall out, but the gist is this:

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) )

maybe there are more elegant solutions with definition of exception characters.

  • Related