How to convert Byte Array to hex string in visual c++?

前端 未结 5 1185
野性不改
野性不改 2021-01-11 16:59

Declaration of a method are following:

//some.h
void TDES_Decryption(BYTE *Data, BYTE *Key, BYTE *InitalVector, int Length);

I am calling t

5条回答
  •  暖寄归人
    2021-01-11 17:48

    Using stringstream, sprintf and other functions in the loop is simply not C++. It's horrible for performance and these kind of functions usually get called a lot (unless you're just writing some things into the log).

    Here's one way of doing it. Writing directly into the std::string's buffer is discouraged because specific std::string implementation might behave differently and this will not work then but we're avoiding one copy of the whole buffer this way:

    #include 
    #include 
    #include 
    
    std::string bytes_to_hex_string(const std::vector &input)
    {
      static const char characters[] = "0123456789ABCDEF";
    
      // Zeroes out the buffer unnecessarily, can't be avoided for std::string.
      std::string ret(input.size() * 2, 0);
    
      // Hack... Against the rules but avoids copying the whole buffer.
      char *buf = const_cast(ret.data());
    
      for (const auto &oneInputByte : input)
      {
        *buf++ = characters[oneInputByte >> 4];
        *buf++ = characters[oneInputByte & 0x0F];
      }
      return ret;
    }
    
    int main()
    {
      std::vector bytes = { 34, 123, 252, 0, 11, 52 };
      std::cout << "Bytes to hex string: " << bytes_to_hex_string(bytes) << std::endl;
    }
    

提交回复
热议问题