I have a large hex string
abcdef...
and I want to convert it to
0xab 0xcd 0xef
Are there any functions
Approximately the following (I wish I could made it shorter and use some library functions, any ideas?):
The function string_to_vector takes a character string and its length as input. It goes over the string, processing two characters (str[ i ] and str[ i + 1 ]) at a time. (For odd values of n, the last pass process only one character (str[ i ] though.) Each character is converted to numeric value using the hex_char_to_int method. Then it constructs a number by "joining" the two numeric values by shifting and adding. Finally, the constructed numeric value is appended to a vector of numeric values which is returned at the end of the function.
std::vector< unsigned >
string_to_vector( const char * str, size_t n ) {
std::vector< unsigned > result;
for( size_t i = 0; i < n; i += 2 ) {
unsigned number = hex_char_to_int( str[ i ] ); // most signifcnt nibble
if( (i + 1) < n ) {
unsigned lsn = hex_char_to_int( str[ i + 1 ] ); // least signt nibble
number = (number << 4) + lsn;
}
result.push_back( number );
}
return result;
}
The following function converts characters in the range [0-9A-Za-z] to the corresponding unsigned int value.
unsigned
hex_char_to_int( char c ) {
unsigned result = -1;
if( ('0' <= c) && (c <= '9') ) {
result = c - '0';
}
else if( ('A' <= c) && (c <= 'F') ) {
result = 10 + c - 'A';
}
else if( ('a' <= c) && (c <= 'f') ) {
result = 10 + c - 'a';
}
else {
assert( 0 );
}
return result;
}