请阅读【嵌入式开发学习必备专栏】
文章目录
- binary to hex
- C code
- 测试效果
- Makefile 编译
binary to hex
在嵌入式开发的过程中经常遇到需要将二进制文件转换为十六进制数组的需求,比如需要将某个镜像文件转换为数组,然后通过写memory的方式将镜像文件加载到内存中。下面代码给出了如何使用C 代码将一个二进制文件转为十六进制数据。
C code
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <inttypes.h>int main(int argc, char *argv[])
{FILE *fpIn, *fpOut;uint32_t buffer[1];uint64_t i = 0x200000000ULL;size_t bytesRead;if (argc < 2) {printf("Usage: %s offset\n", argv[0]);return 1;}const char *file_name = argv[1];/* uint64_t base = atoi(argv[2]); */fpIn = fopen(file_name, "rb");if (fpIn == NULL) {perror("Error opening file");return EXIT_FAILURE;}fpOut = fopen("test_data.h", "w");if (fpOut == NULL) {perror("Error opening file");fclose(fpIn);return EXIT_FAILURE;}fprintf(fpOut, "#ifndef __TEST_DATA_H__\n");fprintf(fpOut, "#define __TEST_DATA_H__\n\n");fprintf(fpOut, "struct test_str test_data[] = {\n");while ((bytesRead = fread(buffer, sizeof(buffer[0]), 1, fpIn)) == 1) {fprintf(fpOut, "{0x%" PRIx64 ",", i);fprintf(fpOut, "0x%08X,},\n", buffer[0]);i += sizeof(buffer[0]);}fprintf(fpOut, "};\n\n");fprintf(fpOut, "#endif // __TEST_DATA_H__\n");fclose(fpIn);fclose(fpOut);return EXIT_SUCCESS;
}
这段代码首先尝试以二进制读取模式打开文件,然后以写模式打开test_data.h
文件。通过fread
函数以4字节为一个单位循环读取数据,每次读取成功后,将读取到的数据以指定格式写入到test_data.h
文件中。
测试效果
#ifndef __TEST_DATA_H__
#define __TEST_DATA_H__struct test_str test_data[] = {
{0x200000000,0x02033000,},
{0x200000004,0x00801F85,},
{0x200000008,0x00802041,},
{0x20000000c,0x00802041,},
{0x200000010,0x00802041,},
{0x200000014,0x00802041,},
{0x200000018,0x00802041,},
{0x20000001c,0x00000000,},
{0x200000020,0x00000000,},
{0x200000024,0x00000000,},
{0x200000028,0x00000000,},
...
第一列为地址,第二例为数据。
Makefile 编译
# 定义编译器
CC = gcc# 定义编译选项
CFLAGS = -Wall# 定义源文件
SOURCES = bin2hex.c #d.c# 定义目标文件
OBJECTS = $(SOURCES:.c=.o)# 定义可执行文件
EXECUTABLE = bin2hex# 默认目标
all: $(EXECUTABLE)
$(EXECUTABLE): $(OBJECTS)$(CC) $(CFLAGS) $(OBJECTS) -o $@# 通用规则用于从每个.c文件构建.o文件
%.o: %.c$(CC) $(CFLAGS) -c $< -o $@#$(shell awk -F, 'NR >= 0 && $2 != "0x00000000" {print}' test_data.h > demo_firmware.h)# 清理编译产物的目标
clean:rm -f $(OBJECTS) $(EXECUTABLE)