Char array to hex string C++

前端 未结 8 535
时光取名叫无心
时光取名叫无心 2020-12-05 06:42

I searched char* to hex string before but implementation I found adds some non-existent garbage at the end of hex string. I receive pa

相关标签:
8条回答
  • 2020-12-05 07:40

    Code snippet above provides incorrect byte order in string, so I fixed it a bit.

    char const hex[16] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A',   'B','C','D','E','F'};
    
    std::string byte_2_str(char* bytes, int size) {
      std::string str;
      for (int i = 0; i < size; ++i) {
        const char ch = bytes[i];
        str.append(&hex[(ch  & 0xF0) >> 4], 1);
        str.append(&hex[ch & 0xF], 1);
      }
      return str;
    }
    
    0 讨论(0)
  • 2020-12-05 07:41

    Supposing data is a char*. Working example using std::hex:

    for(int i=0; i<data_length; ++i)
        std::cout << std::hex << (int)data[i];
    

    Or if you want to keep it all in a string:

    std::stringstream ss;
    for(int i=0; i<data_length; ++i)
        ss << std::hex << (int)data[i];
    std::string mystr = ss.str();
    
    0 讨论(0)
提交回复
热议问题