add functions to convert from hex strings to other types
authorGerd von Egidy <gerd.von.egidy@intra2net.com>
Mon, 18 Jul 2016 12:11:43 +0000 (14:11 +0200)
committerGerd von Egidy <gerd.von.egidy@intra2net.com>
Mon, 18 Jul 2016 12:11:43 +0000 (14:11 +0200)
src/stringfunc.hxx
test/stringfunc.cpp

index 407b726..7f108a4 100644 (file)
@@ -137,7 +137,6 @@ std::string convert_binary_to_hex(const std::string&str, bool upper_case_digits=
 std::string convert_hex_to_binary(const std::string& str) throw(std::runtime_error);
 
 
-
 /*
 ** "type conversions":
 */
@@ -182,6 +181,46 @@ bool string_to(const std::string& s, T& result)
 
 
 /**
+ * convert string in hexadecimal notation to a datatype @a T
+ * supports strings with and without "0x" notation, e.g. 0xff and FF are both valid
+ * 
+ * @param s the hex string which should be converted to @a T.
+ * @return the value of type T.
+ */
+template<
+class T
+>
+T hex_string_to(const std::string& s)
+{
+   std::istringstream istr(s);
+   T result;
+   istr >> std::hex >> result;
+   return result;
+} // eo string_to(const std::string&)
+
+
+/**
+ * convert string in hexadecimal notation to a datatype @a T
+ * supports strings with and without "0x" notation, e.g. 0xff and FF are both valid
+ *
+ * @param s the hex string which should be converted to @a T.
+ * @param result the resulting value of type @a T.
+ * @return @a true iff the internal string stream was EOF after the conversion.
+ *
+ * @attention: does not return if the conversion was successful. So check for empty strings before.
+ */
+template<
+class T
+>
+bool hex_string_to(const std::string& s, T& result)
+{
+   std::istringstream istr(s);
+   istr >> std::hex >> result;
+   return istr.eof();
+} // eo string_to(const std::string&)
+
+
+/**
  * convert a string to another datatype @a T via string stream.
  *
  * @param v the value (of type @a T) which should be converted to a string.
index 8ced76b..49e44e0 100644 (file)
@@ -34,6 +34,7 @@ on this file might be covered by the GNU General Public License.
 
 #include <stringfunc.hxx>
 #include <containerfunc.hpp>
+#include <iostream>
 
 using namespace std;
 using namespace I2n;
@@ -646,7 +647,7 @@ BOOST_AUTO_TEST_CASE(ConversionStringInt)
 
 
 
-BOOST_AUTO_TEST_CASE(HexConversion)
+BOOST_AUTO_TEST_CASE(HexBinaryConversion)
 {
     std::string hex1("49324E");
     std::string bin1("I2N");
@@ -668,6 +669,13 @@ BOOST_AUTO_TEST_CASE(HexConversion)
     BOOST_REQUIRE_THROW( convert_hex_to_binary("01 kein hex"), std::runtime_error);
 } // eo HexConversion()
 
+BOOST_AUTO_TEST_CASE(HexIntConversion)
+{
+    BOOST_CHECK_EQUAL( 255 , hex_string_to<uint32_t>("ff") );
+    BOOST_CHECK_EQUAL( 18866985 , hex_string_to<uint32_t>("11FE329") );
+    BOOST_CHECK_EQUAL( 44 , hex_string_to<uint32_t>("0x2C") );
+}
+
 BOOST_AUTO_TEST_CASE(sanitize_for_logging1)
 {
     string output = sanitize_for_logging("normaler string ohne aerger");