python將字符串轉成二進制數組
功能概述:
save_binary_to_json() 函數:將字符串轉換為二進制數據(字節的整數表示),并保存到JSON文件中。
load_binary_from_json() 函數:從JSON文件中讀取二進制數據并還原為原始字符串。
核心功能:通過JSON實現字符串的二進制序列化與反序列化。
適用場景:需要將二進制數據存儲為文本格式(如調試、跨平臺傳輸)。
step1:C:\Users\wangrusheng\PycharmProjects\FastAPIProject1\hello.py
import jsondef save_binary_to_json():# 原始字符串original_str = "你好!世界先生!"# 將字符串轉換為二進制數組(字節的整數表示)binary_array = list(original_str.encode('utf-8'))# 將二進制數組保存為JSON文件with open('binary_data.json', 'w') as json_file:json.dump(binary_array, json_file)def load_binary_from_json():# 讀取JSON文件with open('binary_data.json', 'r') as json_file:binary_array = json.load(json_file)# 將二進制數組轉換為字節數據byte_data = bytes(binary_array)# 將字節數據解碼為字符串decoded_str = byte_data.decode('utf-8')return decoded_str# 使用示例
save_binary_to_json() # 保存二進制數據到JSON文件
result = load_binary_from_json() # 從JSON文件讀取并還原字符串
print(result) # 輸出: hello world
step2:C:\Users\wangrusheng\PycharmProjects\FastAPIProject1\binary_data.json
[228, 189, 160, 229, 165, 189, 239, 188, 129, 228, 184, 150, 231, 149, 140, 229, 133, 136, 231, 148, 159, 239, 188, 129]
step3:運行結果
(.venv) PS C:\Users\wangrusheng\PycharmProjects\FastAPIProject1> python hello.py
你好!世界先生!
(.venv) PS C:\Users\wangrusheng\PycharmProjects\FastAPIProject1>
end