utils.py 486 B

1234567891011121314151617181920212223
  1. from typing import Optional
  2. def bytes_to_long(buffer: bytes, buffer_size: Optional[int] = None) -> int:
  3. if buffer_size is not None:
  4. assert len(buffer) == buffer_size
  5. num = 0
  6. for byte in buffer:
  7. num = num * 256 + byte
  8. return num
  9. def long_to_bytes(num: int, buffer_size: int) -> bytes:
  10. assert 0 <= num
  11. buffer = [0] * buffer_size
  12. for i in range(buffer_size):
  13. buffer[-i - 1] = num & 255
  14. num >>= 8
  15. return bytes(buffer)