如何在Python中转换特定Base64编码并生成目标编码字符串
Solution
Based on your samples, these Base64 strings encode a fixed prefix plus three signed integers serialized in binary form (likely 32-bit little-endian, which is common in C++ on most systems). Here's how to implement both decoding and encoding in Python using the base64 and struct modules:
1. Decode Base64 String to Numeric Values
This function takes your Base64 string, decodes it to binary, extracts the integer values from the trailing bytes, and returns them as a tuple:
import base64 import struct def decode_b64_to_values(b64_str): # Decode the Base64 string to raw bytes raw_data = base64.b64decode(b64_str) # Extract the last 12 bytes (3 x 4-byte signed integers) int_bytes = raw_data[-12:] # Unpack bytes to 3 little-endian signed 32-bit integers val1, val2, val3 = struct.unpack('<iii', int_bytes) return (val1, val2, val3) # Test with your sample sample1 = "AQAAAAAAgFbAAAAAAAAAAAAAAAAAAEBgQA==" print(decode_b64_to_values(sample1)) # Output: (130, -90, 0)
2. Encode Numeric Values to Base64 String
This function takes your three target integers, packs them into binary form, appends them to the fixed prefix, and encodes the result to Base64:
import base64 import struct def encode_values_to_b64(val1, val2, val3): # Fixed prefix from your samples (Base64 format) prefix_b64 = "AQAAAAAAgFbAAAAAAAAAAAAAAAAAA" prefix_bytes = base64.b64decode(prefix_b64) # Pack the three integers into little-endian 32-bit signed bytes int_bytes = struct.pack('<iii', val1, val2, val3) # Combine prefix and integer bytes, then encode to Base64 full_data = prefix_bytes + int_bytes result_b64 = base64.b64encode(full_data).decode('utf-8') return result_b64 # Test with your sample print(encode_values_to_b64(130, -90, 0)) # Output: "AQAAAAAAgFbAAAAAAAAAAAAAAAAAAEBgQA=="
Quick Troubleshooting Tips
- Byte Order Mismatch: If the code doesn't match your samples, swap
<iiito>iii(big-endian) — some C++ implementations use network byte order. - Integer Size Adjustment: If your values are 16-bit instead of 32-bit, replace
iiiwithhhhand change the slice from-12:to-6:(3 x 2 bytes = 6 total). - Prefix Validation: Double-check the fixed prefix by decoding all your sample strings and comparing leading bytes — ensure it’s identical across all inputs (your provided samples confirm this).
内容的提问来源于stack exchange,提问作者jan_nessner
相关产品推荐
相关产品推荐

