c++ String到byteArray的转换和加法

C++ String to byteArray Convertion and Addition

本文关键字:转换 String byteArray c++      更新时间:2023-10-16

我有一个字符串,我想把它转换成一个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));