You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

45 lines
796 B

  1. #include "config.h"
  2. #include "util.h"
  3. /* Convert from ASCII hex. Returns
  4. the value, or 16 if it was space/newline, or
  5. 32 if some other character. */
  6. uint8_t from_hex(uint8_t ch)
  7. {
  8. if(ch==' ' || ch=='\r' || ch=='\n')
  9. return 16;
  10. if(ch < '0')
  11. goto bad;
  12. if(ch <= '9')
  13. return ch - '0';
  14. ch |= 0x20;
  15. if(ch < 'a')
  16. goto bad;
  17. if(ch <= 'f')
  18. return ch - 'a' + 10;
  19. bad:
  20. return 32;
  21. }
  22. const uint8_t hex[16]={'0','1','2','3','4','5','6','7',
  23. '8','9','a','b','c','d','e','f'};
  24. /* Convert 4 ASCII hex digits into a 16-bit unsigned number.
  25. Returns the number, or -1 if there's an error */
  26. int32_t hex_to_u16(char x[4])
  27. {
  28. uint16_t v = 0;
  29. uint8_t t;
  30. int i;
  31. for (i = 0; i < 4; i++) {
  32. t = from_hex(x[i]);
  33. if (t >= 16)
  34. return -1;
  35. v = (v << 4) | t;
  36. }
  37. return v;
  38. }