programing

파일을 C/C++ 소스 코드 배열로 변환하는 스크립트/도구

sourcejob 2022. 9. 22. 00:18
반응형

파일을 C/C++ 소스 코드 배열로 변환하는 스크립트/도구

바이너리 파일을 읽고 (파일 내용을 나타내는) C/C++ 소스 코드 어레이를 출력하는 스크립트/툴이 필요합니다.있어요?


(이 질문은 이전에 삭제되었습니다.이 질문은 가치가 있기 때문에 다시 넣었습니다.구글에서 바로 이걸 검색했는데 아무것도 못 찾았어요.물론 나 자신을 코드화하는 것은 사소한 일이지만, 만약 내가 그런 간단한 대본을 찾을 수 있었다면 나는 몇 분 동안 시간을 절약할 수 있었을 것이다.그래서 가치가 있다.

이 질문들은 또한 많은 설명 없이 투표율이 낮았다.왜 이것이 가치가 없거나 나쁜 가치가 없다고 생각하는지 다운투표를 하기 전에 코멘트를 해 주세요.

이 질문도 제가 무엇을 묻고 있는지 많은 혼란을 일으켰습니다.뭔가 불명확한 점이 있으면 물어보세요.어떻게 더 명확히 해야 할지 모르겠어요.예에 대해서는, 회답을 참조해 주세요.

또, (질문을 여기에 넣은 후에) 벌써 몇개의 답을 가지고 있습니다.다른 사용자가 찾는 데 도움이 될 수 있기 때문에 여기에 추가/링크하고 싶습니다.

On Debian 및 기타 Linux Distros는 기본적으로 설치됩니다(및vim)의xxd툴, 이 툴은-i옵션, 원하는 대로 할 수 있습니다.

matteo@teodeb:~/Desktop$ echo Hello World\! > temp
matteo@teodeb:~/Desktop$ xxd -i temp 
unsigned char temp[] = {
  0x48, 0x65, 0x6c, 0x6c, 0x6f, 0x20, 0x57, 0x6f, 0x72, 0x6c, 0x64, 0x21,
  0x0a
};
unsigned int temp_len = 13;

*nix와 같은 시스템이라면 xxd 툴을 사용한 답변이 좋습니다.패스상에 python 실행 파일이 있는 시스템의 「원라이너」를 다음에 나타냅니다.

python -c "import sys;a=sys.argv;open(a[2],'wb').write(('const unsigned char '+a[3]+'[] = {'+','.join([hex(b) for b in open(a[1],'rb').read()])+'};').encode('utf-8'))" <binary file> <header file> <array name>

< binary file >은 C 헤더로 변환하는 파일 이름, <header file >은 헤더 파일 이름, <array name >은 어레이에 할당하는 이름입니다.

위의 한 줄의 Python 명령어는 다음 Python 프로그램과 거의 같은 동작을 합니다(더 읽기 쉽게).

import sys

with open(sys.argv[2],'wb') as result_file:
  result_file.write(b'const char %s[] = {' % sys.argv[3].encode('utf-8'))
  for b in open(sys.argv[1], 'rb').read():
    result_file.write(b'0x%02X,' % b)
  result_file.write(b'};')

사용 가능한 모든 옵션을 확인하고 변환을 수행할 수 있는 작은 프로그램을 만들기로 했습니다.

https://github.com/TheLivingOne/bin2array/blob/master/bin2array.c

bin2c나 xxd보다 훨씬 빠르게 동작합니다.이것은 특히 빌드 시스템에 변환을 포함시키고 싶은 경우에 큰 파일에 중요합니다.예: 컴퓨터에 있는 50Mb 파일의 경우:

bin2c.py > 20초

간단한 Python 스크립트 - 약 10초

xxd - 약 3초

bin2array - 약 0.4초

또한 32비트 또는 64비트 값을 입력할 경우에 대비하여 훨씬 더 콤팩트한 출력을 생성하고 어레이에 정렬을 추가합니다.

한 가지 간단한 도구는 다음과 같습니다.

#include <stdio.h>
#include <assert.h>

int main(int argc, char** argv) {
    assert(argc == 2);
    char* fn = argv[1];
    FILE* f = fopen(fn, "rb");
    printf("char a[] = {\n");
    unsigned long n = 0;
    while(!feof(f)) {
        unsigned char c;
        if(fread(&c, 1, 1, f) == 0) break;
        printf("0x%.2X,", (int)c);
        ++n;
        if(n % 10 == 0) printf("\n");
    }
    fclose(f);
    printf("};\n");
}

이 도구는 C에서 개발자 명령 프롬프트를 컴파일합니다.생성된 "array_name.c" 파일의 내용을 표시하는 출력을 단말기에 생성합니다.일부 단말기는 "\b" 문자를 표시할 수 있습니다.

    #include <stdio.h>
    #include <assert.h>

    int main(int argc, char** argv) {
    assert(argc == 2);
    char* fn = argv[1];

    // Open file passed by reference
    FILE* f = fopen(fn, "rb");
    // Opens a new file in the programs location
    FILE* fw = fopen("array_name.c","w");

    // Next two lines write the strings to the console and .c file
    printf("char array_name[] = {\n");
    fprintf(fw,"char hex_array[] = {\n");

    // Declare long integer for number of columns in the array being made
    unsigned long n = 0;

    // Loop until end of file
    while((!feof(f))){
        // Declare character that stores the bytes from hex file
        unsigned char c;

        // Ignore failed elements read
        if(fread(&c, 1, 1, f) == 0) break;
        // Prints to console and file, "0x%.2X" ensures format for all
        // read bytes is like "0x00"
        printf("0x%.2X,", (int)c);
        fprintf(fw,"0x%.2X,", (int)c);

        // Increment counter, if 20 columns have been made, begin new line
        ++n;
        if(n % 20 == 0){
            printf("\n");
            fprintf(fw,"\n");
        }
    }

    // fseek places cursor to overwrite extra "," made from previous loop
    // this is for the new .c file. Since "\b" is technically a character
    // to remove the extra "," requires overwriting it.
    fseek(fw, -1, SEEK_CUR);

    // "\b" moves cursor back one in the terminal
    printf("\b};\n");
    fprintf(fw,"};\n");
    fclose(f);
    fclose(fw);
}

이것은 Albert의 답변과 동일한 프로그램인 C 어레이 제너레이터 파이썬 소스 코드에 대한 바이너리 파일입니다.

import sys
from functools import partial

if len(sys.argv) < 2:
  sys.exit('Usage: %s file' % sys.argv[0])
print("char a[] = {")
n = 0
with open(sys.argv[1], "rb") as in_file:
  for c in iter(partial(in_file.read, 1), b''):
    print("0x%02X," % ord(c), end='')
    n += 1
    if n % 16 == 0:
      print("")
print("};")

오래된 질문이지만, 대체 수단으로 사용할 수 있는 간단한 도구를 제안합니다.

Fluid라는 GUI 기반 도구를 사용할 수 있습니다.실제로는 FLTK 툴킷의 인터페이스를 설계하는 데 사용되지만 바이너리 파일에서 C++용 부호 없는 char 배열을 생성할 수도 있습니다.muquit에서 다운로드하세요.

유체 스크린샷

언급URL : https://stackoverflow.com/questions/8707183/script-tool-to-convert-file-to-c-c-source-code-array

반응형