HexDecode.c 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. /*
  2. * The Python Imaging Library.
  3. * $Id$
  4. *
  5. * decoder for hex encoded image data
  6. *
  7. * history:
  8. * 96-05-16 fl Created
  9. *
  10. * Copyright (c) Fredrik Lundh 1996.
  11. * Copyright (c) Secret Labs AB 1997.
  12. *
  13. * See the README file for information on usage and redistribution.
  14. */
  15. #include "Imaging.h"
  16. #define HEX(v) \
  17. ((v >= '0' && v <= '9') ? v - '0' \
  18. : (v >= 'a' && v <= 'f') ? v - 'a' + 10 \
  19. : (v >= 'A' && v <= 'F') ? v - 'A' + 10 \
  20. : -1)
  21. int
  22. ImagingHexDecode(Imaging im, ImagingCodecState state, UINT8 *buf, Py_ssize_t bytes) {
  23. UINT8 *ptr;
  24. int a, b;
  25. ptr = buf;
  26. for (;;) {
  27. if (bytes < 2) {
  28. return ptr - buf;
  29. }
  30. a = HEX(ptr[0]);
  31. b = HEX(ptr[1]);
  32. if (a < 0 || b < 0) {
  33. ptr++;
  34. bytes--;
  35. } else {
  36. ptr += 2;
  37. bytes -= 2;
  38. state->buffer[state->x] = (a << 4) + b;
  39. if (++state->x >= state->bytes) {
  40. /* Got a full line, unpack it */
  41. state->shuffle(
  42. (UINT8 *)im->image[state->y], state->buffer, state->xsize);
  43. state->x = 0;
  44. if (++state->y >= state->ysize) {
  45. /* End of file (errcode = 0) */
  46. return -1;
  47. }
  48. }
  49. }
  50. }
  51. }