How to Convert unsigned char* to std::string in C++?

前端 未结 6 1363
予麋鹿
予麋鹿 2020-11-29 02:56

I have unsigned char*, want to convert it to std::string. Can you please tell me the safest way to do this?

6条回答
  •  失恋的感觉
    2020-11-29 03:19

    You just needed to cast the unsigned char into a char as the string class doesn't have a constructor that accepts unsigned char:

    unsigned char* uc;
    std::string s( reinterpret_cast< char const* >(uc) ) ;
    

    However, you will need to use the length argument in the constructor if your byte array contains nulls, as if you don't, only part of the array will end up in the string (the array up to the first null)

    size_t len;
    unsigned char* uc;
    std::string s( reinterpret_cast(uc), len ) ;
    

提交回复
热议问题