_binary.py 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. #
  2. # The Python Imaging Library.
  3. # $Id$
  4. #
  5. # Binary input/output support routines.
  6. #
  7. # Copyright (c) 1997-2003 by Secret Labs AB
  8. # Copyright (c) 1995-2003 by Fredrik Lundh
  9. # Copyright (c) 2012 by Brian Crowell
  10. #
  11. # See the README file for information on usage and redistribution.
  12. #
  13. """Binary input/output support routines."""
  14. from __future__ import annotations
  15. from struct import pack, unpack_from
  16. def i8(c: bytes) -> int:
  17. return c[0]
  18. def o8(i: int) -> bytes:
  19. return bytes((i & 255,))
  20. # Input, le = little endian, be = big endian
  21. def i16le(c: bytes, o: int = 0) -> int:
  22. """
  23. Converts a 2-bytes (16 bits) string to an unsigned integer.
  24. :param c: string containing bytes to convert
  25. :param o: offset of bytes to convert in string
  26. """
  27. return unpack_from("<H", c, o)[0]
  28. def si16le(c: bytes, o: int = 0) -> int:
  29. """
  30. Converts a 2-bytes (16 bits) string to a signed integer.
  31. :param c: string containing bytes to convert
  32. :param o: offset of bytes to convert in string
  33. """
  34. return unpack_from("<h", c, o)[0]
  35. def si16be(c: bytes, o: int = 0) -> int:
  36. """
  37. Converts a 2-bytes (16 bits) string to a signed integer, big endian.
  38. :param c: string containing bytes to convert
  39. :param o: offset of bytes to convert in string
  40. """
  41. return unpack_from(">h", c, o)[0]
  42. def i32le(c: bytes, o: int = 0) -> int:
  43. """
  44. Converts a 4-bytes (32 bits) string to an unsigned integer.
  45. :param c: string containing bytes to convert
  46. :param o: offset of bytes to convert in string
  47. """
  48. return unpack_from("<I", c, o)[0]
  49. def si32le(c: bytes, o: int = 0) -> int:
  50. """
  51. Converts a 4-bytes (32 bits) string to a signed integer.
  52. :param c: string containing bytes to convert
  53. :param o: offset of bytes to convert in string
  54. """
  55. return unpack_from("<i", c, o)[0]
  56. def i16be(c: bytes, o: int = 0) -> int:
  57. return unpack_from(">H", c, o)[0]
  58. def i32be(c: bytes, o: int = 0) -> int:
  59. return unpack_from(">I", c, o)[0]
  60. # Output, le = little endian, be = big endian
  61. def o16le(i: int) -> bytes:
  62. return pack("<H", i)
  63. def o32le(i: int) -> bytes:
  64. return pack("<I", i)
  65. def o16be(i: int) -> bytes:
  66. return pack(">H", i)
  67. def o32be(i: int) -> bytes:
  68. return pack(">I", i)