参考自:《Linux 命令xxd输出十六进制》
《Python实现Linux命令xxd -i功能》
Linux下的xxd命令,能将一个给定文件或标准输入转换为十六进制形式,也能将十六进制转换回二进制形式。
一. Linux命令xxd
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | Usage: xxd [options] [infile [outfile]] or xxd -r [-s [-]offset] [-c cols] [-ps] [infile [outfile]] Options: -a toggle autoskip: A single '*' replaces nul-lines. Default off. -b binary digit dump (incompatible with -ps,-i,-r). Default hex. -c cols format <cols> octets per line. Default 16 (-i: 12, -ps: 30). -E show characters in EBCDIC. Default ASCII. -g number of octets per group in normal output. Default 2. -h print this summary. -i output in C include file style. -l len stop after <len> octets. -ps output in postscript plain hexdump style. -r reverse operation: convert (or patch) hexdump into binary. -r -s off revert with <off> added to file positions found in hexdump. -s [+][-]seek start at <seek> bytes abs. (or +: rel.) infile offset. -u use upper case hex letters. -v show version: "xxd V1.10 27oct98 by Juergen Weigert". |
二. Linux xxd -i功能
Linux系统xxd命令使用二进制或十六进制格式显示文件内容。若未指定outfile参数,则将结果显示在终端屏幕上;否则输出到outfile中。详细的用法可参考linux命令xxd。
本文主要关注xxd命令
1 2 3 4 | unsigned char test[] = {<!-- --> 0x31, 0x32, 0x33, 0x34, 0x35, 0x0a }; unsigned int test_len = 6; |
可见,数组名即输入文件名(若有后缀名则点号替换为下划线)。注意,0x0a表示换行符LF,即’\n’。
三. xxd -i常见用途
当设备没有文件系统或不支持动态内存管理时,有时会将二进制文件(如引导程序和固件)内容存储在C代码静态数组内。此时,借助xxd命令就可自动生成版本数组。举例如下:
- 使用Linux命令xdd将二进制文件VdslBooter.bin转换为16进制文件DslBooter.txt:
1 | xxd -i < VdslBooter.bin > DslBooter.txt |
其中,’-i’选项表示输出为C包含文件的风格(数组方式)。重定向符号’<'将VdslBooter.bin文件内容重定向到标准输入,该处理可剔除数组声明和长度变量定义,使输出仅包含16进制数值。
- 在C代码源文件内定义相应的静态数组:
1 2 3 4 5 6 7 | static const uint8 bootImageArray[] = {<!-- --> #include " ../../DslBooter.txt" }; TargetImage bootImage = {<!-- --> (uint8 *) bootImageArray, sizeof(bootImageArray) / sizeof(bootImageArray[0]) }; |
编译源码时,DslBooter.txt文件的内容会自动展开到上述数组内。通过巧用#include预处理指令,可免去手工拷贝数组内容的麻烦。
四. xxd其他选项用法
- 以每组两个字节十六进制输出:
xxd test
- 以每组一个字节按大写字母十六进制输出:
xxd -g 1 -u test
- 以每组一个字节按C风格数组十六进制输出:
xxd -g 1 -i test
- 把十六进制文件转换为二进制:
xxd -r demo16revert.txt demorevert.txt