Lua小程序十六进制字符串和二进制数据间的转换 从十六进制字符串转为二进制数: 1 #! /usr/local/bin/lua 2 3 4 --Note: Input hex string file's content must be 5 --a upper case hex string 6 7 --Check the arguments 8 if #arg ~= 2 then 9 print("Usage: <Input Hex String File> <Output Bytes File>\n"); 10 (); 11 end 12 13 --Open input hex string file 14 local hexstrfile = (arg[1], "rb"); 15 if nil == hexstrfile then 16 print("Can not open input file!\n"); 17 (); 18 end 19 20 --Read from the hex string file 21 local hexstr = hexstrfile:read("*a"); 22 if nil == hexstr then 23 print("Can not read hex string from input file!\n"); 24 elseif 1 == (hexstr)%2 then 25 print("Hex string size must be evel!\n"); 26 (); 27 else 28 print("Hex String:", hexstr, "\n"); 29 end 30 31 --Close hex string file 32 hexstrfile:close(); 33 34 --Open output binary file 35 local bytesfile = (arg[2], "wb"); 36 if nil == bytesfile then 37 print("Can not open output file to write!\n"); 38 (); 39 end 40 41 --Convert hex string to bytes 42 for i = 1, (hexstr) - 1, 2 do 43 local doublebytestr = (hexstr, i, i+1); 44 local n = tonumber(doublebytestr, 16); 45 if 0 == n then 46 bytesfile:write('\00'); 47 else 48 bytesfile:write(("%c", n)); 49 end 50 end 51 52 --Close output binary file 53