Patrick Georgi | 593124d | 2020-05-10 19:44:08 +0200 | [diff] [blame] | 1 | /* SPDX-License-Identifier: GPL-2.0-only */ |
Duncan Laurie | b955284 | 2016-05-09 10:58:03 -0700 | [diff] [blame] | 2 | |
Joel Kitching | 393c71c | 2019-06-16 16:09:42 +0800 | [diff] [blame] | 3 | #include <ctype.h> |
Duncan Laurie | b955284 | 2016-05-09 10:58:03 -0700 | [diff] [blame] | 4 | #include <lib.h> |
Duncan Laurie | b955284 | 2016-05-09 10:58:03 -0700 | [diff] [blame] | 5 | |
| 6 | size_t hexstrtobin(const char *str, uint8_t *buf, size_t len) |
| 7 | { |
| 8 | size_t count, ptr = 0; |
| 9 | uint8_t byte; |
| 10 | |
| 11 | for (byte = count = 0; str && *str; str++) { |
| 12 | uint8_t c = *str; |
| 13 | |
| 14 | if (!isxdigit(c)) |
| 15 | continue; |
| 16 | if (isdigit(c)) |
| 17 | c -= '0'; |
| 18 | else |
| 19 | c = tolower(c) - 'a' + 10; |
| 20 | |
| 21 | byte <<= 4; |
| 22 | byte |= c; |
| 23 | |
| 24 | if (++count > 1) { |
| 25 | if (ptr >= len) |
| 26 | return ptr; |
| 27 | buf[ptr++] = byte; |
| 28 | byte = count = 0; |
| 29 | } |
| 30 | } |
| 31 | |
| 32 | return ptr; |
| 33 | } |