_binary.py 1.8 KB

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