Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>There are several approaches possible. The simplest and the most portable is to break the characters down into two character <code>std::string</code>, using each to initialize an <code>std::istringstream</code>, set up the correct format flags, and read the value from that. A somewhat more efficient solution would be to create a single string, inserted whitespace to separate the individual values, and just use one <code>std::istringstream</code>, something like: </p> <pre><code>std::vector&lt;uint8_t&gt; convert4UChars( std::string const&amp; in ) { assert( in.size() &gt;= 8 ); std::string tmp( in.begin(), in.begin() + 8 ); int i = tmp.size(); while ( i &gt; 2 ) { i -= 2; tmp.insert( i, 1, ' '); } std::istringstream s(tmp); s.setf( std::ios_base::hex, std::ios_base::basefield ); std::vector&lt;int&gt; results( 4 ); s &gt;&gt; results[0] &gt;&gt; results[1] &gt;&gt; results[2] &gt;&gt; results[3]; if ( !s ) { // error... } return std::vector&lt;uint8_t&gt;( results.begin(), results.end() ); } </code></pre> <p>If you really want to do it by hand, the alternative is to create a 256 entry table, indexed by each character, and use that:</p> <pre><code>class HexValueTable { std::array&lt;uint_t, 256&gt; myValues; public: HexValueTable() { std::fill( myValues.begin(), myValues.end(), -1 ); for ( int i = '0'; i &lt;= '9'; ++ i ) { myValues[ i ] = i - '0'; } for ( int i = 'a'; i &lt;= 'f'; ++ i ) { myValues[ i ] = i - 'a' + 10; } for ( int i = 'A'; i &lt;= 'A'; ++ i ) { myValues[ i ] = i - 'a' + 10; } } uint8_t operator[]( char ch ) const { uint8_t results = myValues[static_cast&lt;unsigned char&gt;( ch )]; if ( results == static_cast&lt;unsigned char&gt;( -1 ) ) { // error, throw some exceptions... } return results; } }; std::array&lt;uint8_t, 4&gt; convert4UChars( std::string const&amp; in ) { static HexValueTable const hexValues; assert( in.size() &gt;= 8 ); std::array&lt;uint8_t, 4&gt; results; std::string::const_iterator source = in.begin(); for ( int i = 0; i &lt; 4; ++ i ) { results[i] = (hexValues[*source ++]) &lt;&lt; 4; results[i] |= hexValues[*source ++]; } return results; } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload