2016-02-19 43 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