如何在visual c中将字节数组转换为十六进制字符串?

新手上路,请多包涵

方法的声明如下:

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

我从以下代码调用此方法:

 //some.c
extern "C" __declspec(dllexport) bool _cdecl OnDecryption(LPCTSTR stringKSN, LPCTSTR BDK){
    TDES_Decryption(m_Track1Buffer, m_cryptoKey, init_vector, len);
    return m_Track1Buffer;
}

Where as data type of m_Track1Buffer is BYTE m_Track1Buffer[1000]; Now i want to make some changes in above method ie want to return the String in hex instead of Byte 。我应该如何将此 m_Track1buffer 转换为 Hex string

原文由 Amit Pal 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 792
1 个回答

在循环中使用 stringstreamsprintf 和其他函数根本不是 C++。这对性能来说很糟糕,而且这类函数通常会被调用很多(除非你只是在日志中写一些东西)。

这是一种方法。不鼓励直接写入 std::string 的缓冲区,因为特定的 std::string 实现可能会有不同的行为,这将不起作用,但我们通过这种方式避免了整个缓冲区的一个副本:

 #include <iostream>
#include <string>
#include <vector>

std::string bytes_to_hex_string(const std::vector<uint8_t> &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.
  auto buf = const_cast<char *>(ret.data());

  for (const auto &oneInputByte : input)
  {
    *buf++ = characters[oneInputByte >> 4];
    *buf++ = characters[oneInputByte & 0x0F];
  }
  return ret;
}

int main()
{
  std::vector<uint8_t> bytes = { 34, 123, 252, 0, 11, 52 };
  std::cout << "Bytes to hex string: " << bytes_to_hex_string(bytes) << std::endl;
}

原文由 BJovke 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题