使用C样式转义序列转义二进制文件

时间:2016-02-19 18:21:27

标签: c bash shell

我有一个小的二进制文件。我想将该二进制文件作为字符数组导入C程序,如下所示:

char some_binary_data[] = "\000-type or \xhh-type escape sequences and such here";

是否有标准的shell命令可以使用C风格的转义呈现二进制数据?如果我可以在八进制样式转义和十六进制转义之间进行选择,则可以获得奖励积分。

例如,如果我的文件包含字节

0000000 117000 060777 000123
0000006

,我想将其呈现为"\000\236\377a\123"

2 个答案:

答案 0 :(得分:1)

根据我的知识,并没有完全像这样,但是" od"如果你在* nix世界或mac中,那就很接近了。不知道windoz。

这是一个shell脚本

#!/bin/bash

if [ ! -f "$1" ]; then
        echo file "$1" does not exist
        exit
        fi

if [ -z $2 ]; then
        echo output file not specfied
        exit
        fi

echo "char data[]=" > $2
od -t x1 $1 |awk '/[^ ]*  *[^ ]/ {printf("      \"");for(i=2;i<=NF;++i)printf("\\x%s", $i); print "\""}' >> $2
echo "  ;" >> $2

答案 1 :(得分:1)

这是我放在一起应该有用的东西:

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <ctype.h>

int main(int argc, char *argv[])
{
    int infile = open(argv[1], O_RDONLY);
    if (infile == -1) {
        perror("open failed");
        exit(1);
    }

    FILE *outfile = fopen(argv[2],"w");
    if (!outfile) {
        perror("fopen failed");
        exit(1);
    }
    fprintf(outfile, "char %s[] = ", argv[3]);

    int buflen;
    int totallen, i, linelen;
    char buf[1000];
    totallen = 0;
    linelen = atoi(argv[4]);
    while ((buflen=read(infile, buf, sizeof(buf))) > 0) {
        for (i=0;i<buflen;i++) {
            if (totallen % linelen == 0) {
                fprintf(outfile, "\"");
            }
            if (buf[i] == '\"' || buf[i] == '\\') {
                fprintf(outfile,"\\%c",buf[i]);
            } else if (isalnum(buf[i]) || ispunct(buf[i]) || buf[i] == ' ') {
                fprintf(outfile,"%c",buf[i]);
            } else {
                fprintf(outfile,"\\x%02X",buf[i]);
            }
            if (totallen % linelen == linelen - 1) {
                fprintf(outfile, "\"\n    ");
            }
            totallen++;
        }
    }
    if (totallen % linelen != 0) {
        fprintf(outfile, "\"");
    }
    fprintf(outfile, ";\n");

    close(infile);
    fclose(outfile);
    return 0;
}

示例输入:

This is a "test".  This is only a \test.

被称为:

/tmp/convert /tmp/test1 /tmp/test1.c test1 10

示例输出

char test1[] = "This is a "
    "\"test\".  Th"
    "is is only"
    "a \\test.\x0A"
    ;