_binary.py 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  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 i32le(c, o=0):
  35. """
  36. Converts a 4-bytes (32 bits) string to an unsigned integer.
  37. :param c: string containing bytes to convert
  38. :param o: offset of bytes to convert in string
  39. """
  40. return unpack_from("<I", c, o)[0]
  41. def si32le(c, o=0):
  42. """
  43. Converts a 4-bytes (32 bits) string to a signed 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 i16be(c, o=0):
  49. return unpack_from(">H", c, o)[0]
  50. def i32be(c, o=0):
  51. return unpack_from(">I", c, o)[0]
  52. # Output, le = little endian, be = big endian
  53. def o16le(i):
  54. return pack("<H", i)
  55. def o32le(i):
  56. return pack("<I", i)
  57. def o16be(i):
  58. return pack(">H", i)
  59. def o32be(i):
  60. return pack(">I", i)