c++ String到byteArray的转换和加法
C++ String to byteArray Convertion and Addition
我有一个字符串,我想把它转换成一个byteArray,然后我想把这个byteArray添加到另一个byteArray,但是在byteArray的开头。
假设这是字符串
string suffix = "$PMARVD";
这是我现有的byteArray(忽略这里的对象,它是一个。proto对象,现在无关紧要):
int size = visionDataMsg.ByteSize(); // see how big is it
char* byteArray = new char[size]; //create a bytearray of that size
visionDataMsg.SerializeToArray(byteArray, size); // serialize it
那么我要做的就是像这样:
char* byteArrayforSuffix = suffix.convertToByteArray();
char* byteArrayforBoth = byteArrayforSuffix + byteArray;
无论如何在c++中做这个?
编辑:我应该补充一下,在连接操作之后,完整的byteArrayforBoth将在:
中处理// convert bytearray to vector
vector<unsigned char> byteVector(byteArrayforBoth, byteArrayforBoth + size);
std::string
背后的整个想法是用一个管理一切的类包装C风格字符串(空终止字符/字节数组)。
可以使用std::string::data
方法来扩展内部字符数组。例子:
std::string hello ("hello") , world(" world");
auto helloWorld = hello + world;
const char* byteArray = helloWorld.data();
编辑:ByteArray是char[]
或unsigned char[]
的内置类型,不像Java或c#,你不能只是"追加"内置字节数组到另一个。正如您所建议的,您只需要一个无符号字符的向量。在这种情况下,我只需创建一个利用push_back
:
void appendBytes(vector<unsigend char>& dest,const char* characterArray,size_t size){
dest.reserve(dest.size() + size);
for (size_t i=0;i<size;i++){
dest.push_back(characterArray[i]);
}
}
现在,与您提供的对象:
std::vector<unsigned char> dest;
appendBytes(dest, suffix.data(),suffix.size());
auto another = visionDataMsg.SerializeToArray(byteArray, size);
appendBytes(dest,another,size);
废弃内置数组。你有向量。这里是完全工作的,类型安全的解决方案,我花了3分钟输入:
int size = visionDataMsg.ByteSize(); // see how big is it
std::vector<char> byteArray(size);
visionDataMsg.SerializeToArray(&byteArray[0], size); // serialize it
std::string str("My String");
byteArray.reserve(byteArray.size() + str.size());
std::copy(str.begin(), str.end(), std::back_inserter(byteArray));
相关文章:
- 使用char类型将decimal转换为string,将string转换为decimal
- C++:如何将 unix 时间的字符串转换为 *tm?(使用时间错误:"cannot convert 'String' to 'tm*' ")
- 将C++ std::string 转换为 UTF-16-LE 编码的字符串
- 将日语 wstring 转换为 std::string
- 如何将带有十六进制值的 std::string 转换为 std::vector<无符号字符>
- 如何在 std::string 和 Aws::String 之间进行转换?
- C++:将模板类型 char 转换为 std::string
- 无法<string>从"常量字符 []"转换为<类名>
- 将 std::string( "x3BxDEx7C" ) 转换为可读的十六进制字符串?
- 如何在 c++ 中将向量转换为<string>常量字符* const*?
- 无法从'const std::string [3]'转换为'std::string'
- 从 std::string 转换为 const 无符号整数
- 使用 .data() 将字符数组转换为 std::string 不会转换整个数组
- 为什么std::string没有(显式)const char*强制转换
- 将单个字符转换为 std::string 前缀 \x01
- C++ 模板函数无法将"std:string"转换为"double"作为回报
- 将 std::string 转换为 const char* 用于 printf 消耗
- Swig无法将python3的字节对象转换为std::string
- 将utf16宽std::wstring转换为utf8窄std::string以获得罕见字符时出现问题
- 将 std::string 转换为 const tchar*