convenience.py 592 B

123456789101112131415161718192021222324
  1. # SPDX-FileCopyrightText: 2018-2022 Espressif Systems (Shanghai) CO LTD
  2. # SPDX-License-Identifier: Apache-2.0
  3. #
  4. # Convenience functions for commonly used data type conversions
  5. def bytes_to_long(s: bytes) -> int:
  6. return int.from_bytes(s, 'big')
  7. def long_to_bytes(n: int) -> bytes:
  8. if n == 0:
  9. return b'\x00'
  10. return n.to_bytes((n.bit_length() + 7) // 8, 'big')
  11. # 'deadbeef' -> b'deadbeef'
  12. def str_to_bytes(s: str) -> bytes:
  13. return bytes(s, encoding='latin-1')
  14. # 'deadbeef' -> b'\xde\xad\xbe\xef'
  15. def hex_str_to_bytes(s: str) -> bytes:
  16. return bytes.fromhex(s)