Looyao's Blog

记录一些点滴

使用hexdump的format格式化输出

| Comments

hexdump可以显示文件的16进制, 当然也不只16进制, 这篇文主要写下如何使用hexdump的format来格式化输出.

先举个例子

bash$ hexdump -e '4/1 "%02x,"' -e '"\n"' tmp.txt
68,65,6c,6c,
6f,20,77,6f,
72,6c,64,0a,

这里4/1表示每行打印4个(1个字节的16进制表示). 再看一个例子,

bash$ hexdump -v -e '4/2 "%02x,"' -e '"\n"' tmp.txt
6568,6c6c,206f,6f77,
6c72,a64,  ,  ,

这里4/2, 这里4/2表示每行打印4个(2个字节的16进制表示). 而后边的%02x和C语言的printf 格式化字串一样. -v选项是防止输出多余的*字符.

这样, 使用hexdump命令的format就可以很方便的输出我们需要的格式了. 比如现在要把图片数据赋值到程序变量中, 我们可以先使用hexdump 格式化输出图片数据:

bash$ hexdump -v -e '/1 "0x%02x,"' close.png
0x89,0x50,0x4e,0x47,0x0d,0x0a,0x1a,0x0a,0x00,0x00,0x00,0x0d,0x49,0x48,0x44,0x52,0x00,0x00,0x00,0x1e,0x00,0x00,0x00,0x1e,0x08,0x06,0x00,0x00,0x00,0x3b,0x30,0xae,0xa2,0x00,0x00,0x00,0x09,0x70,0x48,0x59,0x73,0x00,0x00,0x0b,(...后边省略)

在c代码中

unsigned char img_data[] = {0x89,0x50,0x4e,0x47,0x0d,0x0a,0x1a,0x0a,0x00,0x00,0x00,0x0d,0x49,0x48,0x44,0x52,0x00,0x00,0x00,0x1e,0x00,0x00,0x00,0x1e,0x08,0x06,0x00,0x00,0x00,0x3b,0x30,0xae,0xa2,0x00,0x00,0x00,0x09,0x70,0x48,0x59,0x73,0x00,0x00,0x0b,(...后边省略)};

Comments