我正在读取一个在STM32上具有代码的二进制文件。我在代码中放置了故意的2个const字符串,这使我可以从给定文件中读取SW版本和说明。
使用十六进制编辑器甚至在python3中打开二进制文件时,都可以看到正确的格式。但是,当运行text = data.decode('utf-8', errors='ignore')
时,它将从文件中删除零!我不希望这样,因为我会保持EOL字符正确分割并提取我感兴趣的字符串。
(数据变量结尾的预览)
Svc \ x00 .. \ Src \ adc.c \ x00 .. \ Src \ can.c \ x00defaultTask \ x00Task_CANbus_receive \ x00Task_LED_Controller \ x00Task_LED1_TX \ x00Task_LED2_RX \ x00Task_PWM_Controller \ x00 ** SW_VER:GN_1.01 \ x00 \ x00 x00 \ x00 \ x00 \ x00MODULE_DESC:通用模块\ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 ** Task_SuperVisor_Controller \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x01 \ x02 \ x03 \ x04 \ x06 \ x07 \ x08 \ t \ x00 \ x00 \ x00 \ x00 \ x01 \ x02 \ x03 \ x04 .. \ Src \ tim.c \ x005!\ x00 \ x08 \ x11!\ x00 \ x08 \ x01 \ x00 \ x00 \ x00 \ xaa \ xaa \ xaa \ xaa \ xaa \ x01 \ x01 \ nd \ x00 \ x02 \ x04 \ nd \ x00 \ x00 \ x00 \ x00 \ xa2J \ x04'
(文本预览,即解码后我收到的内容)
r g @ IDLE TmrQ Tmr Svc .. \ Src \ adc.c .. \ Src \ can.c defaultTask Task_CANbus_receive Task_LED_Controller Task_LED1_TX Task_LED2_RX Task_PWM_Controller SW_VER:GN_1.01
MODULE_DESC:generic_module
Task_SuperVisor_Controller .. \ Src \ tim.c 5! ! d d J
with open(path_to_file, "rb") as binary_file:
# Read the whole file at once
data = binary_file.read()
text = data.decode('utf-8', errors='ignore')
# get index of "SW_VER:" sting in the file
sw_ver_index = text.rfind("SW_VER:")
# SW_VER found
if sw_ver_index is not -1:
# retrive the value, e.g. "SW_VER:WB_2.01" will has to start from position 7 and finish at 14
sw_ver_value = text[sw_ver_index + 7:sw_ver_index + 14]
module.append(tuple(('DESC:', sw_ver_value)))
else:
# SW_VER not found
module.append(tuple(('DESC:', 'N/A')))
# get index of "MODULE_DESC::" sting in the file
module_desc_index = text.rfind("MODULE_DESC:")
# MODULE_DESC found
if module_desc_index is not -1:
module_desc_substring = text[module_desc_index + 12:]
module_desc_value = module_desc_substring.split()
module.append(tuple(('DESC:', module_desc_value[0])))
print(module_desc_value[0])
您可以看到我的白色字符不见了,而应该出现