C++ Byte转十六进制字符串输出
生活随笔
收集整理的這篇文章主要介紹了
C++ Byte转十六进制字符串输出
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
代碼
例子一
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
總結
以上是生活随笔為你收集整理的C++ Byte转十六进制字符串输出的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 「已回复」396是什么意思考研
- 下一篇: Hello OpenGL——OpenGL