
参考自:《Linux 命令xxd输出十六进制》
《Python实现Linux命令xxd -i功能》
Linux下的xxd命令,能将一个给定文件或标准输入转换为十六进制形式,也能将十六进制转换回二进制形式。
一. Linux命令xxd 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 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 octets. -ps output in postscript plain hexdump style. -r reverse operation: convert (or patch) hexdump into binary. -r -s off revert with added to file positions found in hexdump. -s [+][-]seek start at 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命令
-i
选项。使用该选项可输出以inputfile为名的C语言数组定义。例如,执行
echo 12345 > test
和
xxd -i test
命令后,输出为:
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: xxd -i DslBooter.txt
其中,’-i’选项表示输出为C包含文件的风格(数组方式)。重定向符号’
来电咨询