【问题标题】:Escaping a binary file with C-style escape sequences [duplicate]使用 C 风格的转义序列转义二进制文件 [重复]
【发布时间】:2016-06-01 10:25:30
【问题描述】:

我有一个小的二进制文件。我想将该二进制文件作为字符数组导入 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"

【问题讨论】:

  • 你反对写一个这样的小程序吗?这将是一个相当简单的程序。
  • 这是一个骗局,但是,xxd 工具正是您要找的。请参阅this superuser answer,了解在哪里可以获得适用于 Windows 的设备。它应该安装在任何安装了 vim 的现代 Unix 上,例如在 RHEL 上,它位于 vim-common 包中。

标签: c bash shell


【解决方案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"
    ;

【讨论】:

  • 谢谢,这很好,但有点不理想。字符串“这是一个测试。这只是一个测试。”已经正确逃脱;你刚刚把它变成了一个更大的、正确转义的字符串。我宁愿只在必要时逃避事情。
  • @BrandonYarbrough 我做了一个快速更新,只逃避需要的东西。
  • 很酷,谢谢!
【解决方案2】:

据我所知,没有一个完全一样的,但如果你在 *nix 世界或 mac 中,“od”很接近。不知道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

【讨论】:

    猜你喜欢
    • 2018-02-05
    • 1970-01-01
    • 2017-04-06
    • 2020-03-06
    • 1970-01-01
    • 2022-01-13
    • 2020-06-20
    • 2011-06-21
    相关资源
    最近更新 更多