如何将机器码文件及各类文本文件内容存入指定数组?
解决方案
嘿,这两个问题我熟,给你一步步讲清楚怎么实现!
1. 读取二进制机器码文件到数组
如果你的机器码文件是二进制格式(直接存储字节数据,不是文本),读取到数组非常直接:
Python 实现
# 打开二进制机器码文件 with open("machine_code.bin", "rb") as f: # 将二进制内容转换为整数数组(每个字节对应一个整数元素) program = list(f.read())
C 语言实现
#include <stdio.h> #include <stdlib.h> int main() { FILE *fp = fopen("machine_code.bin", "rb"); if (!fp) { perror("Failed to open file"); return 1; } // 获取文件总大小 fseek(fp, 0, SEEK_END); long file_size = ftell(fp); fseek(fp, 0, SEEK_SET); // 分配数组内存 unsigned char *program = malloc(file_size); if (!program) { perror("Failed to allocate memory"); fclose(fp); return 1; } // 读取全部内容到数组 fread(program, 1, file_size, fp); fclose(fp); // 使用完毕后记得释放内存 free(program); return 0; }
2. 读取文本格式的机器码文件(sasm/mach)到数组
针对你说的每行是0x1000 0x30C3 0x11FC这种空格分隔的十六进制文本,要让每行对应数组的一个元素(比如每个元素是该行所有十六进制值组成的整数列表),可以这么做:
Python 实现
program = [] with open("code.mach", "r") as f: for line in f: # 去除每行的空白字符(换行、首尾空格) cleaned_line = line.strip() if not cleaned_line: # 跳过空行 continue # 按空格分割成单个十六进制字符串,转换为整数 hex_values = [int(val, 16) for val in cleaned_line.split()] # 将该行的数值列表作为数组的一个元素存入 program.append(hex_values)
如果需要把每行的十六进制值合并成字节串或单个大整数,也可以调整:
- 合并为字节串:
bytes.fromhex(cleaned_line.replace("0x", "").replace(" ", "")) - 合并为单个整数:
int(cleaned_line.replace("0x", "").replace(" ", ""), 16)
C 语言实现
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #define MAX_LINE_LEN 1024 #define MAX_VALUES_PER_LINE 100 // 定义结构体存储每行的数值和数量 typedef struct { unsigned int values[MAX_VALUES_PER_LINE]; int count; } LineData; int main() { FILE *fp = fopen("code.mach", "r"); if (!fp) { perror("Failed to open file"); return 1; } // 动态数组存储所有行的数据 LineData *program = NULL; int line_count = 0; char line[MAX_LINE_LEN]; while (fgets(line, MAX_LINE_LEN, fp)) { // 跳过注释(假设//为注释符)和空行 char *comment_ptr = strchr(line, '/'); if (comment_ptr) *comment_ptr = '\0'; // 去除行首空白字符 char *trimmed_line = line; while (isspace((unsigned char)*trimmed_line)) trimmed_line++; if (*trimmed_line == '\0') continue; // 重新分配内存,添加新行数据 program = realloc(program, (line_count + 1) * sizeof(LineData)); if (!program) { perror("Failed to allocate memory"); fclose(fp); return 1; } LineData *current_line = &program[line_count]; current_line->count = 0; char *token = strtok(trimmed_line, " \t\n"); // 分割每行的十六进制字符串并转换为整数 while (token != NULL && current_line->count < MAX_VALUES_PER_LINE) { unsigned int val; if (sscanf(token, "%x", &val) == 1) { current_line->values[current_line->count++] = val; } token = strtok(NULL, " \t\n"); } line_count++; } fclose(fp); // 示例:打印第一行的第一个数值 if (line_count > 0 && program[0].count > 0) { printf("First value of first line: 0x%X\n", program[0].values[0]); } // 释放动态内存 free(program); return 0; }
这样处理后,program数组的每个元素就对应文件里的一行内容,完全不用手动编写那些十六进制值啦!
内容的提问来源于stack exchange,提问作者koukah
相关产品推荐
相关产品推荐

