|
| 1 | +/* |
| 2 | + Copyright (c) 2015 Hristo Gochkov. All rights reserved. |
| 3 | + This file is part of the esp32 core for Arduino environment. |
| 4 | +
|
| 5 | + This library is free software; you can redistribute it and/or |
| 6 | + modify it under the terms of the GNU Lesser General Public |
| 7 | + License as published by the Free Software Foundation; either |
| 8 | + version 2.1 of the License, or (at your option) any later version. |
| 9 | +
|
| 10 | + This library is distributed in the hope that it will be useful, |
| 11 | + but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 12 | + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU |
| 13 | + Lesser General Public License for more details. |
| 14 | +
|
| 15 | + You should have received a copy of the GNU Lesser General Public |
| 16 | + License along with this library; if not, write to the Free Software |
| 17 | + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA |
| 18 | +*/ |
| 19 | + |
| 20 | +#include <Arduino.h> |
| 21 | +#include <HEXBuilder.h> |
| 22 | + |
| 23 | +static uint8_t hex_char_to_byte(uint8_t c) |
| 24 | +{ |
| 25 | + return (c >= 'a' && c <= 'f') ? (c - ((uint8_t)'a' - 0xa)) : |
| 26 | + (c >= 'A' && c <= 'F') ? (c - ((uint8_t)'A' - 0xA)) : |
| 27 | + (c >= '0' && c<= '9') ? (c - (uint8_t)'0') : 0x10; // unknown char is 16 |
| 28 | +} |
| 29 | + |
| 30 | +size_t HEXBuilder::hex2bytes(unsigned char * out, size_t maxlen, String &in) { |
| 31 | + return hex2bytes(out, maxlen, in.c_str()); |
| 32 | +} |
| 33 | + |
| 34 | +size_t HEXBuilder::hex2bytes(unsigned char * out, size_t maxlen, const char * in) { |
| 35 | + size_t len = 0; |
| 36 | + for(;*in;in++) { |
| 37 | + uint8_t c = hex_char_to_byte(*in); |
| 38 | + // Silently skip anything unknown. |
| 39 | + if (c > 15) |
| 40 | + continue; |
| 41 | + |
| 42 | + if (len & 1) { |
| 43 | + if (len/2 < maxlen) |
| 44 | + out[len/2] |= c; |
| 45 | + } else { |
| 46 | + if (len/2 < maxlen) |
| 47 | + out[len/2] = c<<4; |
| 48 | + } |
| 49 | + len++; |
| 50 | + } |
| 51 | + return (len + 1)/2; |
| 52 | +} |
| 53 | + |
| 54 | +size_t HEXBuilder::bytes2hex(char * out, size_t maxlen, const unsigned char * in, size_t len) { |
| 55 | + for(size_t i = 0; i < len; i++) { |
| 56 | + if (i*2 + 1 < maxlen) { |
| 57 | + sprintf(out + (i * 2), "%02x", in[i]); |
| 58 | + } |
| 59 | + } |
| 60 | + return len * 2 + 1; |
| 61 | +} |
| 62 | + |
| 63 | +String HEXBuilder::bytes2hex(const unsigned char * in, size_t len) { |
| 64 | + size_t maxlen = len * 2 + 1; |
| 65 | + char * out = (char *) malloc(maxlen); |
| 66 | + if (!out) return String(); |
| 67 | + bytes2hex(out, maxlen, in, len); |
| 68 | + String ret = String(out); |
| 69 | + free(out); |
| 70 | + return ret; |
| 71 | +} |
0 commit comments