hexify.c 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. #include <stdint.h>
  2. #include <string.h>
  3. #include "hexify.h"
  4. static char hexchars[] = "0123456789abcdef0123456789ABCDEF";
  5. /**
  6. * hexify(in, out, len):
  7. * Convert ${len} bytes from ${in} into hexadecimal, writing the resulting
  8. * 2 * ${len} bytes to ${out}; and append a NUL byte.
  9. */
  10. void
  11. hexify(const uint8_t * in, char * out, size_t len)
  12. {
  13. char * p = out;
  14. size_t i;
  15. for (i = 0; i < len; i++) {
  16. *p++ = hexchars[in[i] >> 4];
  17. *p++ = hexchars[in[i] & 0x0f];
  18. }
  19. *p = '\0';
  20. }
  21. /**
  22. * unhexify(in, out, len):
  23. * Convert 2 * ${len} hexadecimal characters from ${in} to ${len} bytes
  24. * and write them to ${out}. This function will only fail if the input is
  25. * not a sequence of hexadecimal characters.
  26. */
  27. int
  28. unhexify(const char * in, uint8_t * out, size_t len)
  29. {
  30. size_t i;
  31. ptrdiff_t pos;
  32. /* Make sure we have at least 2 * ${len} hex characters. */
  33. for (i = 0; i < 2 * len; i++) {
  34. if ((in[i] == '\0') || (strchr(hexchars, in[i]) == NULL))
  35. goto err0;
  36. }
  37. /* Process all pairs of characters. */
  38. for (i = 0; i < len; i++) {
  39. /* Convert first character. */
  40. pos = strchr(hexchars, in[2 * i]) - hexchars;
  41. out[i] = (uint8_t)((pos & 0x0f) << 4);
  42. /* Convert second character. */
  43. pos = strchr(hexchars, in[2 * i + 1]) - hexchars;
  44. out[i] = (uint8_t)(out[i] + (pos & 0x0f));
  45. }
  46. /* Success! */
  47. return (0);
  48. err0:
  49. /* Bad input string. */
  50. return (-1);
  51. }