C ++转换向量< BYTE>到第一个向量字节为0的字符串 [英] C++ Converting Vector<BYTE> to string where first vector byte is 0

查看:122
本文介绍了C ++转换向量< BYTE>到第一个向量字节为0的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将BYTES的std :: vector(或无符号字符)转换为std :: string。
我的问题是向量的第一个元素为0时,转换后返回的是空字符串。

I am trying to convert a std::vector of BYTES (or unsigned char) to a std::string. The problem I have is when the first element of the vector is a 0, then this returns an empty string after the conversion.

我尝试了2下面的方法。 string1和string2都返回一个空字符串。
我期望的结果是一个以2 x 0s开头的字符串,后跟其他几个字符。

I have tried the 2 methods below. Both string1 and string2 return an empty string. The result I am expecting is a string that starts with 2 x 0s followed by several other characters.

// vector of BYTE, contains these 7 elements for example: (0,30,85,160,155,93,0)
std::vector<BYTE> data;

// method 1
BYTE* pByteArray = &data[0];
std::string string1 = reinterpret_cast<LPCSTR>(pByteArray);

// method 2
std::string string2(data.begin(),data.end());

// both string1 and string2 return ""

我猜是因为向量中的第一个BYTE为0,因此字符串分配认为它为null或为空。
为了返回字符串的其余部分,我还可以做一些其他转换吗?

I am guessing because the first BYTE in the vector is a 0, so the string assignment is thinking it's null or empty. Is there some other conversion I can do in order to return the rest of the string?

任何帮助我们都非常感谢。

Any help greatly appreciated.

推荐答案

第二个并不是真的空,请考虑:

The second is not really empty please consider:

// vector of BYTE, contains these 7 elements for example: (0,30,85,160,155,93,0)
std::vector<BYTE> data = {0, 35, 35 ,38};

// method 2
std::string string2(data.begin(),data.end());
cout<< (string2.data()+1) << " size:"<< string2.size() << endl;
/* Notice that size is 4 */

ideone

编辑检查大小甚至更简单它是 4

Edit Checking the size is even more trivial as it's 4.

关于数据 null 作为 docs 友好地解释(强调我的意思):

Regarding data and null termination as the docs kindly explain (emphasis mine):


返回的数组为空终止,是,data()和c_str()执行相同的功能。如果empty()返回true,则指针将
指向单个空字符。 (自C ++ 11起)

The returned array is null-terminated, that is, data() and c_str() perform the same function. If empty() returns true, the pointer points to a single null character. (since C++11)

一种 c ++ 98安全方式可能看起来喜欢

A "c++98 safe" way could look like:

cout.write(string2.data()+1, string2.size()-1); 

无论如何,打印只是为了演示字符串 non-emptiness:)

Anyway the printing is just to demonstrate the strings "non-emptiness" :)

这篇关于C ++转换向量&lt; BYTE&gt;到第一个向量字节为0的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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