파일을 C / C ++ 소스 코드 배열로 변환하는 스크립트 / 도구
바이너리 파일을 읽고 C / C ++ 소스 코드 배열 (파일 내용을 나타냄)을 출력하는 스크립트 / 도구가 필요합니다. 거기 아무도 없나요?
(이 질문은 이전에 삭제되었습니다.이 질문은 가치가 있기 때문에 다시 넣었습니다. Google에서 정확히이 질문을 검색했지만 아무것도 찾지 못했습니다. 물론 직접 코딩하는 것은 사소한 일이지만 몇 분을 절약 할 수 있었을 것입니다. 그런 간단한 스크립트를 찾았을 것입니다.
이 질문에는 많은 설명 없이도 많은 반대표가있었습니다. 이것이 가치가 없거나 나쁜 가치라고 생각하는 이유에 대해 반대 투표하기 전에 의견을 말하십시오.
이 질문은 또한 내가 묻는 것에 대해 많은 혼란을 일으켰습니다. 불명확 한 점이 있으면 물어보세요. 나는 그것을 더 명확하게하는 방법을 정말로 모른다. 예제는 답변을 참조하십시오.
또한 (여기에 질문을 넣은 후) 이미 몇 가지 답변이 있습니다. 다른 사람이 이것을 검색하는 데 유용 할 것이라고 생각하기 때문에 여기 (다시)에 추가 / 연결하고 싶습니다.)
Debian 및 기타 Linux 배포판에서는 기본적으로 (와 함께 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;
#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");
}
* 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>
<바이너리 파일>은 C 헤더로 변환하려는 파일의 이름이고, <헤더 파일>은 헤더 파일의 이름이며, <배열 이름>은 배열에 포함 할 이름입니다.
위의 한 줄 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'};')
이 도구는 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 ++ 용 unsigned char 배열을 생성 할 수도 있습니다. muquit 에서 다운로드하십시오 .
참고URL : https://stackoverflow.com/questions/8707183/script-tool-to-convert-file-to-c-c-source-code-array
'Program Tip' 카테고리의 다른 글
브라우저 간 (피어 투 피어) 연결을 어떻게 만들 수 있습니까? (0) | 2020.11.01 |
---|---|
구성 / 메이크주기에 include 및 lib 경로를 추가하는 방법은 무엇입니까? (0) | 2020.11.01 |
Python : defaultdict를 dict로 변환 (0) | 2020.11.01 |
Dockerfile에서 스크립트 실행 (0) | 2020.11.01 |
Jenkins 용 API 토큰을 얻는 방법 (0) | 2020.11.01 |