Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert Byte Array to Hexadecimal String in C++?

Tags:

c++

string

hex

byte

I am looking for a fastest way to convert a byte array of arbitrary length to a hexadecimal string. This question has been fully answered here at StackOverflow for C#. Some solutions in C++ can be found here.

Are there any "turnkey" or "ready-made" solutions to a problem? C-style solutions are welcome.

like image 712
ezpresso Avatar asked Mar 27 '12 16:03

ezpresso


People also ask

How do you convert bytes to strings?

One method is to create a string variable and then append the byte value to the string variable with the help of + operator. This will directly convert the byte value to a string and add it in the string variable.

How to get hex from byte array c#?

To obtain a string in hexadecimal format from this array, we simply need to call the ToString method on the BitConverter class. As input we need to pass our byte array and, as output, we get the hexadecimal string representing it. string hexString = BitConverter. ToString(byteArray);


1 Answers

#include <vector>
#include <iostream>
#include <algorithm>
#include <string>
#include <iterator>
#include <sstream>
#include <iomanip>

int main() 
{
  std::vector<unsigned char> v;

  v.push_back( 1 );
  v.push_back( 2 );
  v.push_back( 3 );
  v.push_back( 4 );

  std::ostringstream ss;

  ss << std::hex << std::uppercase << std::setfill( '0' );
  std::for_each( v.cbegin(), v.cend(), [&]( int c ) { ss << std::setw( 2 ) << c; } );

  std::string result = ss.str();

  std::cout << result << std::endl;
  return 0;
}

Or, if you've got a compiler that supports uniform initialization syntax and range based for loops you can save a few lines.

#include <vector>
#include <sstream>
#include <string>
#include <iostream>
#include <iomanip>

int main()
{
  std::vector<unsigned char> v { 1, 2, 3, 4 };
  std::ostringstream ss;

  ss << std::hex << std::uppercase << std::setfill( '0' );
  for( int c : v ) {
    ss << std::setw( 2 ) << c;
  }

  std::string result = ss.str();
  std::cout << result << std::endl;
}
like image 158
Praetorian Avatar answered Nov 04 '22 12:11

Praetorian