_binary.py 2.0 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 struct import pack, unpack_from
  15. def i8(c):
  16. return c if c.__class__ is int else c[0]
  17. def o8(i):
  18. return bytes((i & 255,))
  19. # Input, le = little endian, be = big endian
  20. def i16le(c, o=0):
  21. """
  22. Converts a 2-bytes (16 bits) string to an unsigned integer.
  23. :param c: string containing bytes to convert
  24. :param o: offset of bytes to convert in string
  25. """
  26. return unpack_from("<H", c, o)[0]
  27. def si16le(c, o=0):
  28. """
  29. Converts a 2-bytes (16 bits) string to a signed integer.
  30. :param c: string containing bytes to convert
  31. :param o: offset of bytes to convert in string
  32. """
  33. return unpack_from("<h", c, o)[0]
  34. def si16be(c, o=0):
  35. """
  36. Converts a 2-bytes (16 bits) string to a signed integer, big endian.
  37. :param c: string containing bytes to convert
  38. :param o: offset of bytes to convert in string
  39. """
  40. return unpack_from(">h", c, o)[0]
  41. def i32le(c, o=0):
  42. """
  43. Converts a 4-bytes (32 bits) string to an unsigned integer.
  44. :param c: string containing bytes to convert
  45. :param o: offset of bytes to convert in string
  46. """
  47. return unpack_from("<I", c, o)[0]
  48. def si32le(c, o=0):
  49. """
  50. Converts a 4-bytes (32 bits) string to a signed integer.
  51. :param c: string containing bytes to convert
  52. :param o: offset of bytes to convert in string
  53. """
  54. return unpack_from("<i", c, o)[0]
  55. def i16be(c, o=0):
  56. return unpack_from(">H", c, o)[0]
  57. def i32be(c, o=0):
  58. return unpack_from(">I", c, o)[0]
  59. # Output, le = little endian, be = big endian
  60. def o16le(i):
  61. return pack("<H", i)
  62. def o32le(i):
  63. return pack("<I", i)
  64. def o16be(i):
  65. return pack(">H", i)
  66. def o32be(i):
  67. return pack(">I", i)