如何在 C++ 中将 unsigned char* 转换为 std::string? [英] How to Convert unsigned char* to std::string in C++?

查看:88
本文介绍了如何在 C++ 中将 unsigned char* 转换为 std::string?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有unsigned char*,想把它转换成std::string.你能告诉我最安全的方法吗?

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

推荐答案

您只需要将 unsigned char 转换为 char 作为 string 类没有接受 unsigned char 的构造函数:

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<char const*>(uc), len ) ;

这篇关于如何在 C++ 中将 unsigned char* 转换为 std::string?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆