14 lines
472 B
Python
14 lines
472 B
Python
|
|
def string_to_bytes_fixed_size(src: str, size: int, encoding='utf-8') -> bytes:
|
|
assert type(src) is str, "src must be a string"
|
|
src_bin = src.encode(encoding)
|
|
while len(src_bin) > size:
|
|
src = src[:-1]
|
|
src_bin = src.encode(encoding)
|
|
return src_bin + b'\x00' * (size - len(src_bin))
|
|
|
|
|
|
def bytes_to_string(src: bytes, encoding='utf-8') -> str:
|
|
assert type(src) is bytes, "src must be bytes"
|
|
return src.decode(encoding).rstrip('\x00')
|