bytespec.c 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. /*====================================================================*
  2. *
  3. * size_t bytespec (char const *string, void * memory, size_t extent);
  4. *
  5. * memory.h
  6. *
  7. * encode a memory region with a fixed-length hexadecimal string;
  8. * return the number of bytes encoded or terminate the program on
  9. * error;
  10. *
  11. * the number of octets in string must equal the memory extent or
  12. * an error will occur; octets may be seperated by colons; empty
  13. * octets are illegal;
  14. *
  15. * Motley Tools by Charles Maier;
  16. * Copyright (c) 2001-2006 by Charles Maier Associates;
  17. * Licensed under the Internet Software Consortium License;
  18. *
  19. *--------------------------------------------------------------------*/
  20. #ifndef BYTESPEC_SOURCE
  21. #define BYTESPEC_SOURCE
  22. #include <ctype.h>
  23. #include <errno.h>
  24. #include "../tools/memory.h"
  25. #include "../tools/number.h"
  26. #include "../tools/error.h"
  27. size_t bytespec (char const * string, void * memory, size_t extent)
  28. {
  29. char const * number = string;
  30. byte * origin = (byte *)(memory);
  31. byte * offset = (byte *)(memory);
  32. if (!number)
  33. {
  34. error (1, EINVAL, "bytespec");
  35. }
  36. while (isspace (*number))
  37. {
  38. number++;
  39. }
  40. while ((*number) && (extent))
  41. {
  42. unsigned digit;
  43. if ((offset > origin) && (*number == HEX_EXTENDER))
  44. {
  45. number++;
  46. }
  47. if ((digit = todigit (*number++)) >= RADIX_HEX)
  48. {
  49. error (1, EINVAL, "You said '%s' but I want a hex digit", string);
  50. }
  51. *offset = digit << 4;
  52. if ((digit = todigit (*number++)) >= RADIX_HEX)
  53. {
  54. error (1, EINVAL, "You said '%s' but I want a hex digit", string);
  55. }
  56. *offset |= digit;
  57. offset++;
  58. extent--;
  59. }
  60. while (isspace (*number))
  61. {
  62. number++;
  63. }
  64. if ((*number) || (extent))
  65. {
  66. error (1, EINVAL, "%s is not %d bytes", string, (unsigned)(offset - origin + extent));
  67. }
  68. return (offset - origin);
  69. }
  70. #endif