Duncan Laurie | b955284 | 2016-05-09 10:58:03 -0700 | [diff] [blame] | 1 | /* |
| 2 | * Copyright 2016 Google Inc. |
| 3 | * |
| 4 | * This program is free software; you can redistribute it and/or modify |
| 5 | * it under the terms of the GNU General Public License as published by |
| 6 | * the Free Software Foundation; version 2 of the License. |
| 7 | * |
| 8 | * This program is distributed in the hope that it will be useful, |
| 9 | * but without any warranty; without even the implied warranty of |
| 10 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 11 | * GNU General Public License for more details. |
| 12 | */ |
| 13 | |
Joel Kitching | 393c71c | 2019-06-16 16:09:42 +0800 | [diff] [blame] | 14 | #include <ctype.h> |
Duncan Laurie | b955284 | 2016-05-09 10:58:03 -0700 | [diff] [blame] | 15 | #include <lib.h> |
Duncan Laurie | b955284 | 2016-05-09 10:58:03 -0700 | [diff] [blame] | 16 | |
| 17 | size_t hexstrtobin(const char *str, uint8_t *buf, size_t len) |
| 18 | { |
| 19 | size_t count, ptr = 0; |
| 20 | uint8_t byte; |
| 21 | |
| 22 | for (byte = count = 0; str && *str; str++) { |
| 23 | uint8_t c = *str; |
| 24 | |
| 25 | if (!isxdigit(c)) |
| 26 | continue; |
| 27 | if (isdigit(c)) |
| 28 | c -= '0'; |
| 29 | else |
| 30 | c = tolower(c) - 'a' + 10; |
| 31 | |
| 32 | byte <<= 4; |
| 33 | byte |= c; |
| 34 | |
| 35 | if (++count > 1) { |
| 36 | if (ptr >= len) |
| 37 | return ptr; |
| 38 | buf[ptr++] = byte; |
| 39 | byte = count = 0; |
| 40 | } |
| 41 | } |
| 42 | |
| 43 | return ptr; |
| 44 | } |