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

前端 未结 4 2075
别跟我提以往
别跟我提以往 2020-12-17 22:29

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

4条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-17 22:55

    #include 
    #include 
    #include 
    #include 
    #include 
    #include 
    #include 
    
    int main() 
    {
      std::vector 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 
    #include 
    #include 
    #include 
    #include 
    
    int main()
    {
      std::vector 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;
    }
    

提交回复
热议问题