|
发表于 2024-10-5 17:15:58
|
显示全部楼层
当然可以!我们可以增加一个参数来指定总数据量,并在数据不足时进行补零。同时,调整输出顺序以符合您的要求。以下是修改后的代码示例:
- def hex_to_bin(hex_string, total_bytes, bytes_per_group):
- # 去掉hex_string中的空格和换行,以及地址标记
- hex_string = hex_string.replace(' ', '').replace('\n', '')
- hex_string = ''.join(line for line in hex_string.split('@') if not line.startswith('0000'))
- # 计算总数据长度
- num_bytes = len(hex_string) // 2
- if num_bytes < total_bytes:
- hex_string += '00' * (total_bytes - num_bytes) # 补零
- # 从数据中提取每个字节,并转换成二进制字符串
- bin_data = []
- for i in range(0, len(hex_string), 2):
- byte_value = hex_string[i:i + 2]
- # 这里使用int转换为二进制并填充到8位
- bin_str = format(int(byte_value, 16), '08b')
- bin_data.append(bin_str)
- # 按指定字节数分组并进行翻转
- result = []
- for i in range(0, len(bin_data), bytes_per_group):
- group = bin_data[i:i + bytes_per_group]
- group.reverse() # 翻转字节顺序
- result.extend(group)
- return result
- def write_bin_file(output_filename, bin_data):
- # 将二进制数据写入文件,每32位一行
- with open(output_filename, 'w') as file:
- for i in range(0, len(bin_data), 4):
- file.write(''.join(bin_data[i:i + 4]) + '\n')
- if __name__ == "__main__":
- hex_filename = 'input.hex'
- output_filename = 'output.bin'
- total_bytes = 64 # 根据需要调整总数据量(例如64字节)
- bytes_per_group = 4 # 每组翻转的字节数(例如4字节)
- # 从文件中读取HEX数据
- with open(hex_filename, 'r') as file:
- hex_data = file.read()
- # 转换并写入输出文件
- bin_data = hex_to_bin(hex_data, total_bytes, bytes_per_group)
- write_bin_file(output_filename, bin_data)
复制代码
这个脚本会从`input.hex`中读取HEX数据,进行翻转和补零处理,并将结果写入`output.bin`。你可以根据你的实际数据和需要调整`total_bytes`和`bytes_per_group`。
以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。 |
|