From 7084fb70257871d60a3ad70a2c98fec67a8f7d52 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gr=C3=A9gory=20Soutad=C3=A9?= Date: Sat, 27 Aug 2022 15:40:32 +0200 Subject: [PATCH] Add fromHex() static function to ByteArray --- include/bytearray.h | 9 ++++++++- src/bytearray.cpp | 42 ++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 50 insertions(+), 1 deletion(-) diff --git a/include/bytearray.h b/include/bytearray.h index e2f8d29..8fb7680 100644 --- a/include/bytearray.h +++ b/include/bytearray.h @@ -104,6 +104,13 @@ namespace gourou */ std::string toBase64(); + /** + * @brief Convert hex string into bytes + * + * @param str Hex string + */ + static ByteArray fromHex(const std::string& str); + /** * @brief Return a string with human readable hex encoded internal data */ @@ -130,7 +137,7 @@ namespace gourou void append(const std::string& str); /** - * @brief Get internal data. Must bot be freed + * @brief Get internal data. Must not be freed */ unsigned char* data() {return _data;} diff --git a/src/bytearray.cpp b/src/bytearray.cpp index fdaeed9..f7ec87f 100644 --- a/src/bytearray.cpp +++ b/src/bytearray.cpp @@ -17,6 +17,7 @@ along with libgourou. If not, see . */ #include +#include #include @@ -155,6 +156,47 @@ namespace gourou return macaron::Base64::Encode(std::string((char*)_data, _length)); } + ByteArray ByteArray::fromHex(const std::string& str) + { + if (str.size() % 2) + throw std::invalid_argument("Size of hex string not multiple of 2"); + + ByteArray res((unsigned int)(str.size()/2)); + unsigned int i; + + unsigned char* data = res.data(); + unsigned char cur, tmp; + + for (i=0; i= 'a' && tmp <= 'f') + cur = (tmp - 'a' + 10) << 4; + else if (tmp >= 'A' && tmp <= 'F') + cur = (tmp - 'A' + 10) << 4; + else if (tmp >= '0' && tmp <= '9') + cur = (tmp - '0') << 4; + else + throw std::invalid_argument("Invalid character in hex string"); + + tmp = str[i+1]; + if (tmp >= 'a' && tmp <= 'f') + cur += tmp - 'a' + 10; + else if (tmp >= 'A' && tmp <= 'F') + cur += tmp - 'A' + 10; + else if (tmp >= '0' && tmp <= '9') + cur += tmp - '0'; + else + throw std::invalid_argument("Invalid character in hex string"); + + data[i/2] = cur; + } + + return res; + } + std::string ByteArray::toHex() { char* tmp = new char[_length*2+1];