代码
例子一
typedef std::vector<unsigned char> bytes;
std::string BytesToStr(const bytes& in)
{bytes::const_iterator from = in.cbegin();bytes::const_iterator to = in.cend();std::ostringstream oss;for (; from != to; ++from)oss << std::hex << std::setw(2) << std::setfill('0') << static_cast<int>(*from);return oss.str();
}
例子二
const string toHexString(char* input, const int datasize){string output;char ch[3];for(int i = 0; i < datasize; ++i){sprintf_s(ch, 3, "%02x", input[i]);output += ch;}return output;
}
例子三
const string ToHexString(char* input, const int datasize)
{char output[33];for(int j = 0; j < datasize; j++ ){unsigned char b = *(input+j);sprintf_s( output+j * 2,3, "%02x",b);}return string(output) ;
}
总体代码
#include <string>
#include <sstream>
#include <vector>
#include <iomanip>
#include <iostream>using namespace std;typedef std::vector<unsigned char> bytes;
std::string BytesToStr(const bytes& in)
{bytes::const_iterator from = in.cbegin();bytes::const_iterator to = in.cend();std::ostringstream oss;for (; from != to; ++from)oss << std::hex << std::setw(2) << std::setfill('0') << static_cast<int>(*from);return oss.str();
}//const string toHexString(char* input, const int datasize)
//
//{
// string output;
// char ch[3];
//
// for(int i = 0; i < datasize; ++i)
// {
// sprintf_s(ch, 3, "%02x", input[i]);
// output += ch;
// }
// return output;
//}const string ToHexString(char* input, const int datasize)
{char output[33];for(int j = 0; j < datasize; j++ ){unsigned char b = *(input+j);sprintf_s( output+j * 2,3, "%02x",b);}return string(output) ;
}int main() {char a[]{ '0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0' };bytes input(a, a + 16);for (auto i : input) {std::cout << i;}std::cout << std::endl;std::cout << "char类型数据 转十六进制 输出: ";//std::cout << BytesToStr(input) << std::endl;std::cout << byteToHexStr(a,16) << std::endl;
}
参考链接
- c++ byte类型数组转十六进制字符串的几种代码实现_yuanyuan_186的专栏-CSDN博客_c++ 字节数组转16进制
- C/C++ equivalent to java Integer.toHexString - Stack Overflow
- Char array to hex string C++ - Stack Overflow
- How to visualize bytes with C/C++ - Stack Overflow
- c++ - Convert bytes array to Hexadecimal String - Stack Overflow