在硬件调试过程中经常遇到十六进制和字符串互相转换的情况。
下面是用Lua写的字符串与16进制串互转函数:
16进制转字符串,如“\x12\x34\xAB\xCD”转为“1234ABCD”。
字符串转16进制,如“1234ABCD”转为“\x12\x34\xAB\xCD”。正常将返回转换后的字符串。
函数里加入了过滤分隔符,可以过滤掉大部分分隔符(可参见正则表达式中\s和\p的范围)。
如果内容不合法,如字符串里包含非0-F的字符,则返回nil。如果字符串长度不是偶数,也返回nil。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
--将16进制串转换为字符串 function hex2str(hex) --判断输入类型 if (type(hex)~="string") then return nil,"hex2str invalid input type" end --拼接字符串 local index=1 local ret="" for index=1,hex:len() do ret=ret..string.format("%02X",hex:sub(index):byte()) end return ret end --将字符串按格式转为16进制串 function str2hex(str) --判断输入类型 if (type(str)~="string") then return nil,"str2hex invalid input type" end --滤掉分隔符 str=str:gsub("[%s%p]",""):upper() --检查内容是否合法 if(str:find("[^0-9A-Fa-f]")~=nil) then return nil,"str2hex invalid input content" end --检查字符串长度 if(str:len()%2~=0) then return nil,"str2hex invalid input lenth" end --拼接字符串 local index=1 local ret="" for index=1,str:len(),2 do ret=ret..string.char(tonumber(str:sub(index,index+1),16)) end return ret end |