diff options
author | Szczepan Zalega <szczepan@nitrokey.com> | 2016-09-09 10:18:46 +0200 |
---|---|---|
committer | Szczepan Zalega <szczepan@nitrokey.com> | 2016-09-10 10:51:53 +0200 |
commit | 77ea27f25165302491a693051bea05c67e6dfbed (patch) | |
tree | ec35346b64dfed3e05282c393f1074fc81bf9c5c | |
parent | 9d84244156e8abd93a7c1d4326231bcd1abb909d (diff) | |
download | libnitrokey-77ea27f25165302491a693051bea05c67e6dfbed.tar.gz libnitrokey-77ea27f25165302491a693051bea05c67e6dfbed.tar.bz2 |
Add hex to binary converting function
Signed-off-by: Szczepan Zalega <szczepan@nitrokey.com>
-rw-r--r-- | include/misc.h | 4 | ||||
-rw-r--r-- | misc.cc | 26 |
2 files changed, 29 insertions, 1 deletions
diff --git a/include/misc.h b/include/misc.h index cccd830..5fcd16d 100644 --- a/include/misc.h +++ b/include/misc.h @@ -2,6 +2,7 @@ #define MISC_H #include <stdio.h> #include <string> +#include <vector> namespace nitrokey { namespace misc { @@ -16,7 +17,8 @@ typename T::CommandPayload get_payload(){ std::string hexdump(const char *p, size_t size, bool print_header=true); -uint32_t stm_crc32(const uint8_t *data, size_t size); + uint32_t stm_crc32(const uint8_t *data, size_t size); + std::vector<uint8_t> hex_string_to_byte(const char* hexString); } } @@ -2,10 +2,36 @@ #include <string> #include "misc.h" #include "inttypes.h" +#include <cstdlib> +#include <cstring> +#include <cassert> namespace nitrokey { namespace misc { +std::vector<uint8_t> hex_string_to_byte(const char* hexString){ + const size_t s_size = strlen(hexString); + const size_t d_size = (s_size+1)/2; // add 1 for odd, ignore for even + assert(s_size%2==0); + assert(s_size<256); //arbitrary 'big' number + auto data = std::vector<uint8_t>(d_size, 0); + + char buf[2]; + for(int i=0; i<s_size; i++){ + + char c = hexString[i]; + bool char_from_range = ('0' <= c && c <='9' || 'A' <= c && c <= 'F' || 'a' <= c && c<= 'f'); + if (!char_from_range){ + return {}; + } + buf[i%2] = c; + if (i%2==1){ + data[i/2] = strtoul(buf, NULL, 16) & 0xFF; + } + } + return data; +}; + std::string hexdump(const char *p, size_t size, bool print_header) { std::stringstream out; char formatbuf[128]; |