1

I am searching the method to convert hex string into byte string in C++. I want to convert s1 into s2 like below pseudo code. The output of to_byte_string must be std::string.

std::string s1 = "0xb5c8d7 ...";
std::string s2;

s2 = to_byte_string(s1) /* s2 == "\xb5\xc8\xd7 ..." */

Is there any library function to do this kind of thing ?

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
xiaofo
  • 57
  • 1
  • 2
  • 5
  • 2
    Basically a dupe of [this](https://stackoverflow.com/questions/17261798/converting-a-hex-string-to-a-byte-array). You can use `s2` in place of the arrays/vectors the answers use. – NathanOliver Oct 01 '19 at 15:39

1 Answers1

0

There is no such a standard function that does the task.But it is not difficult to write an appropriate method by yourself.

For example you can use an ordinary loop or a standard algorithm as for example std::accumulate.

Here is a demonstrative program

#include <iostream>
#include <string>
#include <iterator>
#include <numeric>
#include <cctype>

int main() 
{
    std::string s1( "0xb5c8d7" );

    int i = 1;
    auto s2 = std::accumulate( std::next( std::begin( s1 ), 2 ),
                               std::end( s1 ),
                               std::string(),
                               [&i]( auto &acc, auto byte )
                               {
                                    byte = std::toupper( ( unsigned char )byte );
                                    if ( '0' <= byte && byte <= '9' ) byte -= '0';
                                    else byte -= 'A' - 10;

                                    if ( i ^= 1 ) acc.back() |= byte;
                                    else acc += byte << 4;

                                    return acc;
                               } );

    return 0;
}
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335