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];