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));
BUG=None
BRANCH=None
TEST=None
Change-Id: I2de9bd28ae8c42cdca09eec11a3bba497a52988c
Original-Signed-off-by: Duncan Laurie <dlaurie@chromium.org>
Original-Reviewed-on: https://review.coreboot.org/14837
Original-Tested-by: build bot (Jenkins)
Original-Reviewed-by: Aaron Durbin <adurbin@chromium.org>
Signed-off-by: Aaron Durbin <adurbin@chromium.org>
Reviewed-on: https://chromium-review.googlesource.com/346987
Commit-Ready: Martin Roth <martinroth@chromium.org>
Tested-by: Martin Roth <martinroth@chromium.org>
Reviewed-by: Martin Roth <martinroth@chromium.org>
44 lines
954 B
C
44 lines
954 B
C
/*
|
|
* 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 <lib.h>
|
|
#include <string.h>
|
|
|
|
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;
|
|
}
|