早上在阅读Linux kernel scriptes中的源代码的时候发现bin2c的源代码,于是打算看一下,结果发现"\x"的写法,于是查了点资料,看了一下它的用法。
/****************************************************************************
* Linux kernel scriptes bin2c "\x"
* 声明:
* 早上在阅读Linux kernel scriptes中的源代码的时候发现bin2c的源代码,
* 于是打算看一下,结果发现"\x"的写法,于是查了点资料,看了一下它的用法。
*
* 2015-12-29 深圳 南山平山村 曾剑锋
***************************************************************************/
一、参考资料:
1. \x49\x51\x5a\x56\x54\ 这种是什么编码?
http://zhidao.baidu.com/link?url=tDpw0M4dsxvnldOAzJg0HiS25vYl3ebTBwJOF0ULHxBGEF-0nYLiewaX29d870N5cro-yv2blYWgG2Kx4xFPXK
2. \X在C语言里表示什么意思?
http://zhidao.baidu.com/link?url=HC1lXt3Cv2yE1gQaLchbyhlaAwU9X9hVEQNz_dRqqvP4lTO1dTypMFnKT7rI8mmH9lUsSAjNPgo_fyzJYngcLa
二、Linux内核scripts/bin2c.c
/*
* Unloved program to convert a binary on stdin to a C include on stdout
*
* Jan 1999 Matt Mackall <mpm@selenic.com>
*
* This software may be used and distributed according to the terms
* of the GNU General Public License, incorporated herein by reference.
*/
#include <stdio.h>
/**
* 1. 程序将第二个参数作为数组的名字;
* 2. 程序通过读取标输入数据,并将数据转换成十六进制输出到标准输出;
* 3. 由于是通过标准入获取数据,那么常用的方式应该是采用管道进行数据传输;
* 4. 目前没搞懂下面这条语句为什么要转成"\x":
* printf("\\x%02x",ch);
*/
int main(int argc, char *argv[])
{
int ch, total=0;
if (argc > 1)
printf("const char %s[] %s=\n",
argv[1], argc > 2 ? argv[2] : "");
do {
printf("\t\"");
while ((ch = getchar()) != EOF)
{
total++;
printf("\\x%02x",ch);
if (total % 16 == 0)
break;
}
printf("\"\n");
} while (ch != EOF);
if (argc > 1)
printf("\t;\n\nconst int %s_size = %d;\n", argv[1], total);
return 0;
}
三、"\x"数据测试代码:
#include <stdio.h>
int main (int argc, char **argv) {
printf("%c, %s.\n", '\x30', "\x31\x32");
}