如何将字节数组转换为C ++中的十六进制字符串? [英] How to convert Byte Array to Hexadecimal String in C++?

查看:174
本文介绍了如何将字节数组转换为C ++中的十六进制字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种最快的方式来将任意长度的字节数组转换为十六进制字符串。此问题已完全回答这里在StackOverflow for C#。您可以在此处找到一些C ++解决方案。

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.

是否有任何交钥匙或现成的解决方案?欢迎使用C风格的解决方案。

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

推荐答案

#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;
}

或者,如果你有一个支持统一初始化语法和范围的编译器基于 for 循环您可以保存几行。

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;
}

这篇关于如何将字节数组转换为C ++中的十六进制字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆