如何在Python中将字节串分割为最少的10字节片段以用于重发?
Split Byte String into Minimal 10-Byte Chunks
Got it, this is a super straightforward task once you leverage Python's built-in slicing behavior! Here's a clean, efficient way to split your byte string into the fewest possible 10-byte segments (the last segment will be shorter if your total byte count isn't a multiple of 10):
Solution Code
def split_bytes_into_10byte_chunks(byte_string): # Slice the byte string in steps of 10 to create chunks return [byte_string[i:i+10] for i in range(0, len(byte_string), 10)]
How It Works
range(0, len(byte_string), 10)generates starting indices at 0, 10, 20, etc.—perfect for grabbing each full 10-byte block.- Python's slice notation
byte_string[i:i+10]handles edge cases automatically: ifi+10exceeds the length of the byte string, it just returns whatever bytes are left (no errors, no extra padding). - This ensures you get the minimal number of chunks because every segment is as large as allowed (10 bytes) except the final one, which takes the remainder.
Test with Your Sample Data
Let's run this with the byte string you provided to verify:
sample_bytes = b'\xd3\x00\x16E\xd0\x00q\x1d\xf6?\x80\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x0ff\r' chunks = split_bytes_into_10byte_chunks(sample_bytes) # Print results to check for chunk_num, chunk in enumerate(chunks, 1): print(f"Chunk {chunk_num}: {chunk} (length: {len(chunk)})")
Output
Chunk 1: b'\xd3\x00\x16E\xd0\x00q\x1d\xf6?' (length: 10) Chunk 2: b'\x80\x00\x00\x00\x00\x00\x00\x00\x00\x00' (length: 10) Chunk 3: b'\x00\x00\x00\x00\x00\x0ff\r' (length: 8)
Your 26-byte sample gets split into exactly 3 chunks—the minimal number needed, since 2 full 10-byte blocks plus an 8-byte remainder covers all data.
内容的提问来源于stack exchange,提问作者Team Autonautics
相关产品推荐
相关产品推荐

