2011-04-15 128 views
0

我有一个小的二进制图像,需要在C程序中表示。表示会像:将二进制数据转换为C程序的十六进制字符串

static const char[] = {0x1, 0x2, 0x3, 0x4...}; 

如何转换二进制文件到一个不错的0X(因此,该字节将被表示为一系列字符的)

..,0X ..字符串?有没有一个程序来做到这一点?

+1

http://stackoverflow.com/questions/225480/embed-image-in-code-without-using-resource-section-or-external-images/225658#225658 – 2011-04-15 16:52:43

回答

0

你可以编写一个程序来做到这一点很容易,但这是一个perl script可以为你做。

1

在Python 2.6

from __future__ import with_statement 
with open('myfile.bin') as f: 
    s = f.read() 
    for c in s: 
     print hex(ord(c)) + ",", 
1
#include <stdio.h> 
#include <stdlib.h> 
#include <string.h> 

#define MAX_LENGTH 80 

int main(void) 
{ 
    FILE *fout = fopen("out.txt", "w"); 

    if(ferror(fout)) 
    { 
     fprintf(stderr, "Error opening output file"); 
     return 1; 
    } 
    char init_line[] = {"char hex_array[] = { "}; 
    const int offset_length = strlen(init_line); 

    char offset_spc[offset_length]; 

    unsigned char buff[1024]; 
    char curr_out[64]; 

    int count, i; 
    int line_length = 0; 

    memset((void*)offset_spc, (char)32, sizeof(char) * offset_length - 1); 
    offset_spc[offset_length - 1] = '\0'; 

    fprintf(fout, "%s", init_line); 

    while(!feof(stdin)) 
    { 
     count = fread(buff, sizeof(char), sizeof(buff)/sizeof(char), stdin); 

     for(i = 0; i < count; i++) 
     { 
      line_length += sprintf(curr_out, "%#x, ", buff[i]); 

      fprintf(fout, "%s", curr_out); 
      if(line_length >= MAX_LENGTH - offset_length) 
      { 
       fprintf(fout, "\n%s", offset_spc); 
       line_length = 0; 
      } 
     } 
    } 
    fseek(fout, -2, SEEK_CUR); 
    fprintf(fout, " };"); 

    fclose(fout); 

    return EXIT_SUCCESS; 
} 

在这里,更新,工作。管道在文件中,它将其作为无符号字符数组以十六进制的形式吐出到out.txt文件中。

另一种编辑:想象我可能会很好。打印出来out.txt,一个无符号的字符数组,并很好地格式化。从这里应该是微不足道的,如果你想添加任何东西

0

开源应用Hexy是专门为此设计的。它运行在Windows和Linux上。

0

很好用!但是我做一个小的变化,以允许输入和输出文件要在命令行上指定:

int main(int argc, char **argv) 
{ 
    FILE *fout = NULL; 
    FILE *fin = NULL; 
    const char *optstring = "i:o"; 
    char ch; 
    int argind = 1; 

    if(argc < 5) 
    { 
      fprintf(stderr,"Usage: bin2array -i <input_file> -o <output_file>\n"); 
      return 2; 
    } 

    while((ch = getopt(argc,argv,optstring)) != -1) 
    { 
      switch(ch) 
      { 
      case 'i': 
        argind++; 
        fprintf(stderr,"File: %s\n",argv[argind]); 
        fin = fopen(argv[argind],"rb"); 
        argind++; 
        break; 
      case 'o': 
        argind++; 
        fprintf(stderr,"File: %s\n",argv[argind]); 
        fout = fopen(argv[argind],"wt"); 
        argind++; 
        break; 
      } 
    } 

    .... 
} 
1

如果pBuff是您的二进制数据,尝试找出你的缓冲液,例如长度

lenBuffer= sizeof(..); 
for (i = 0; i < lenBuffer; i++) 
    printf("%x ", pBuff[i]); 
相关问题