Bytes Fields
Bytes fields parse and serialize raw binary data.
Available Types
FixedBytes- Fixed-length bytesBytes- Variable-length bytes (size fromRefor integer)
FixedBytes
Fixed-length bytes field:
from pystructs import Struct, FixedBytes
class Header(Struct):
magic = FixedBytes(length=4)
signature = FixedBytes(length=16)
header = Header.parse(b"\x89PNG" + b"\x00" * 16)
print(header.magic) # b'\x89PNG'
Bytes (Variable-Length)
Variable-length bytes field with size from another field:
from pystructs import Struct, UInt16, Bytes, Ref
class Packet(Struct):
length = UInt16()
data = Bytes(size=Ref("length"))
packet = Packet.parse(b"\x05\x00Hello")
print(packet.data) # b'Hello'
With fixed size:
class Block(Struct):
data = Bytes(size=1024) # Always 1024 bytes
API Reference
- class pystructs.fields.bytes_fields.FixedBytes(length: int, default: bytes | None = None, required: bool = True, validators: List[Callable] | None = None)[source]
Fixed-length bytes field.
- Examples:
>>> class Header(Struct): ... magic = FixedBytes(4) # Always 4 bytes
- class pystructs.fields.bytes_fields.Bytes(size: int | Ref, default: bytes | None = None, required: bool = True, validators: List[Callable] | None = None)[source]
Variable-length bytes field.
Size can be specified as a fixed integer or as a Ref to another field.
- Examples:
>>> class Packet(Struct): ... length = UInt16() ... data = Bytes(size=Ref('length')) # Size from another field ... >>> class Fixed(Struct): ... data = Bytes(size=10) # Fixed size
- get_size(instance: Struct) int[source]
Get the current size of this field.
- Args:
instance: The struct instance
- Returns:
Size in bytes
- parse(buffer: BinaryIO, instance: Struct) bytes[source]
Parse variable bytes from buffer.
- Args:
buffer: Binary stream to read from instance: The struct instance being parsed
- Returns:
Parsed bytes
- Raises:
UnexpectedEOF: If not enough bytes available
- serialize(value: bytes, instance: Struct) bytes[source]
Serialize bytes value.
Note: This is “dumb” serialization - no size validation is performed. Use sync() and validate() for consistency checks.
- Args:
value: Bytes to serialize instance: The struct instance being serialized
- Returns:
The bytes value