From b9552841bf9d1f59e173d9eb082b6e31423e8496 Mon Sep 17 00:00:00 2001 From: Duncan Laurie Date: Mon, 9 May 2016 10:58:03 -0700 Subject: hexstrtobin: Add a library function to decode ASCII hex into binary This function will turn a string of ASCII hex characters into an array of bytes. It will ignore any non-ASCII-hex characters in the input string and decode up to len bytes of data from it. This can be used for turning MAC addresses or UUID strings into binary for storage or further processing. Sample usage: uint8_t buf[6]; hexstrtobin("00:0e:c6:81:72:01", buf, sizeof(buf)); acpigen_emit_stream(buf, sizeof(buf)); Change-Id: I2de9bd28ae8c42cdca09eec11a3bba497a52988c Signed-off-by: Duncan Laurie Reviewed-on: https://review.coreboot.org/14837 Tested-by: build bot (Jenkins) Reviewed-by: Aaron Durbin --- src/lib/Makefile.inc | 1 + src/lib/hexstrtobin.c | 44 ++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 45 insertions(+) create mode 100644 src/lib/hexstrtobin.c (limited to 'src/lib') diff --git a/src/lib/Makefile.inc b/src/lib/Makefile.inc index 734b517b01..b446e10a35 100644 --- a/src/lib/Makefile.inc +++ b/src/lib/Makefile.inc @@ -114,6 +114,7 @@ ramstage-y += cbfs.c ramstage-$(CONFIG_COMMON_CBFS_SPI_WRAPPER) += cbfs_spi.c ramstage-y += lzma.c lzmadecode.c ramstage-y += stack.c +ramstage-y += hexstrtobin.c ramstage-y += wrdd.c ramstage-$(CONFIG_CONSOLE_CBMEM) += cbmem_console.c ramstage-$(CONFIG_BOOTSPLASH) += jpeg.c diff --git a/src/lib/hexstrtobin.c b/src/lib/hexstrtobin.c new file mode 100644 index 0000000000..ed2abc4e8b --- /dev/null +++ b/src/lib/hexstrtobin.c @@ -0,0 +1,44 @@ +/* + * Copyright 2016 Google Inc. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; version 2 of the License. + * + * This program is distributed in the hope that it will be useful, + * but without any warranty; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + */ + +#include +#include + +size_t hexstrtobin(const char *str, uint8_t *buf, size_t len) +{ + size_t count, ptr = 0; + uint8_t byte; + + for (byte = count = 0; str && *str; str++) { + uint8_t c = *str; + + if (!isxdigit(c)) + continue; + if (isdigit(c)) + c -= '0'; + else + c = tolower(c) - 'a' + 10; + + byte <<= 4; + byte |= c; + + if (++count > 1) { + if (ptr >= len) + return ptr; + buf[ptr++] = byte; + byte = count = 0; + } + } + + return ptr; +} -- cgit v1.2.3