2016-02-19 80 views
-1

我有一个小的二进制文件。我想导入二进制文件到C程序中的字符数组,像这样:用C风格转义序列转义二进制文件

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

是否有一个标准的shell命令,可与C风格的转义呈现二进制数据?奖励积分,如果我可以选择八进制转义和十六进制转义。

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

0000000 117000 060777 00
0000006 

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

+3

你是不是写一个小程序,它是什么?这将是一个相当平凡的计划。 –

+2

http://stackoverflow.com/q/8707183/3776858? – Cyrus

+0

这是一个骗局,但是,'xxd'工具就是你要找的。请参阅[此超级用户的答案](http://superuser.com/a/638850),了解Windows的获取位置。它应该安装在任何安装了vim的现代Unix上,例如在RHEL上它是'vim-common'软件包。 –

回答

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" 
    ; 
+0

谢谢,这是相当不错的,但有点不理想。字符串“这是一个测试,这只是一个测试。”已经妥善逃脱;你已经把它变成了一个更大,妥善转义的字符串。我宁愿只在必要时才转义。 –

+0

@BrandonYarbrough我做了一个快速更新,只逃避需要的东西。 – dbush

+0

很酷,谢谢! –

1

根据我的了解,没有一个完全像这样,但如果您处于* 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