Char array to hex string C++

前端 未结 8 644
时光取名叫无心
时光取名叫无心 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:26

    I've found good example here Display-char-as-Hexadecimal-String-in-C++:

      std::vector randomBytes(n);
      file.read(&randomBytes[0], n);
    
      // Displaying bytes: method 1
      // --------------------------
      for (auto& el : randomBytes)
        std::cout << std::setfill('0') << std::setw(2) << std::hex << (0xff & (unsigned int)el);
      std::cout << '\n';
    
      // Displaying bytes: method 2
      // --------------------------
      for (auto& el : randomBytes)
        printf("%02hhx", el);
      std::cout << '\n';
      return 0;
    

    Method 1 as shown above is probably the more C++ way:

    Cast to an unsigned int
    Use std::hex to represent the value as hexadecimal digits
    Use std::setw and std::setfill from to format
    Note that you need to mask the cast int against 0xff to display the least significant byte:
    (0xff & (unsigned int)el).

    Otherwise, if the highest bit is set the cast will result in the three most significant bytes being set to ff.

提交回复
热议问题