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

查看:3881
本文介绍了如何在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) ) ;

但是,如果您的字节数组包含空值,则需要在构造函数中使用length参数,就好像您不包含该数组一样,只有部分数组会以字符串结尾(该数组直到第一个空值)

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天全站免登陆