如何将小端序十六进制字节转换为大端序格式存储?
问题描述
现有一段通过初始值为0的程序计数器读取文件的代码,因每条指令为4字节(32位),故按4字节步长迭代。当前代码如下:
for (i = 0; i < filesize; i += INSTRUCTION_SIZE) { fread(&blob.instruction_memory[i], 1, INSTRUCTION_SIZE, file); } for (program_counter = 0; program_counter < INSTR_MEM_SIZE; program_counter += INSTRUCTION_SIZE) { unsigned char instruction[INSTRUCTION_SIZE]; for (int j = INSTRUCTION_SIZE - 1; j >= 0; j--) { instruction[j] = blob.instruction_memory[program_counter + j]; } init_instruction(instruction); } fclose(file);
代码逻辑为:程序计数器为0时对应第1条指令,为4时对应第2条指令,以此类推。目前读取到的指令字节序列为0x13,0x01,0xF0,0x7F,但需要将其以大端序格式(即0x7F,0xF0,0x01,0x13)存入instruction[]数组,请问该如何修改代码?
解决方案
要实现字节顺序反转(将小端序的读取结果转为大端序存储),只需修改第二个for循环中的内层字节复制逻辑:
for (i = 0; i < filesize; i += INSTRUCTION_SIZE) { fread(&blob.instruction_memory[i], 1, INSTRUCTION_SIZE, file); } for (program_counter = 0; program_counter < INSTR_MEM_SIZE; program_counter += INSTRUCTION_SIZE) { unsigned char instruction[INSTRUCTION_SIZE]; // 修改内层循环,反转字节顺序 for (int k = 0; k < INSTRUCTION_SIZE; k++) { // 将原内存中从后往前的字节依次存入instruction的起始位置 instruction[k] = blob.instruction_memory[program_counter + (INSTRUCTION_SIZE - 1 - k)]; } init_instruction(instruction); } fclose(file);
逻辑说明
- 原代码的内层循环是将
blob.instruction_memory中连续的4字节按原顺序复制到instruction数组,保留了文件中的小端序字节。 - 修改后的循环中,
k从0到3(对应instruction数组的索引0到3),每次取blob.instruction_memory[program_counter + 3 - k]的字节存入instruction[k]:k=0时,取program_counter+3位置的0x7F存入instruction[0]k=1时,取program_counter+2位置的0xF0存入instruction[1]k=2时,取program_counter+1位置的0x01存入instruction[2]k=3时,取program_counter+0位置的0x13存入instruction[3]
最终得到符合要求的大端序instruction数组。
内容的提问来源于stack exchange,提问作者HyperCoderSuperion
相关产品推荐
相关产品推荐

