How to convert Byte Array to Hexadecimal String in C++?

前端 未结 4 2077
别跟我提以往
别跟我提以往 2020-12-17 22:29

I am looking for a fastest way to convert a byte array of arbitrary length to a hexadecimal string. This question has been fully answered here at StackOverflow for C#. Some

4条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-17 22:53

    One of the fastest way I know in C++ 11:

    template 
    string BytesArrayToHexString( const std::array& src )
    {
      static const char table[] = "0123456789ABCDEF";
      std::array dst;
      const byte* srcPtr = &src[0];
      char* dstPtr = &dst[0];
    
      for (auto count = byteCount; count > 0; --count)
      {
          unsigned char c = *srcPtr++;
          *dstPtr++ = table[c >> 4];
          *dstPtr++ = table[c & 0x0f];
      }
      *dstPtr = 0;
      return &dst[0];
    }
    

    A good compiler should not have any problem to apply SSE optimization on this....

提交回复
热议问题