搜档网

搜档网

当前位置:搜档网 > Lua小程序 十六进制字符串和二进制数据间的转换

Lua小程序 十六进制字符串和二进制数据间的转换

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

8if#arg ~= 2 then

9print("Usage:hexstr2bytes.lua \n"); 10os.exit();

11 end

12

13 --Open input hex string file

14 local hexstrfile = io.open(arg[1], "rb");

15if nil == hexstrfile then

16print("Can not open input file!\n");

17os.exit();

18 end

19

20 --Read from the hex string file

21 local hexstr = hexstrfile:read("*a");

22if nil == hexstr then

23print("Can not read hex string from input file!\n");

24 elseif 1 == string.len(hexstr)%2 then

25print("Hex string size must be evel!\n");

26os.exit();

27else

28print("Hex String:", hexstr, "\n");

29 end

30

31 --Close hex string file

32 hexstrfile:close();

33

34 --Open output binary file

35 local bytesfile = io.open(arg[2], "wb");

36if nil == bytesfile then

37print("Can not open output file to write!\n");

38os.exit();

39 end

40

41 --Convert hex string to bytes

42for i = 1, string.len(hexstr) - 1, 2 do

TOP相关主题