簡體   English   中英

C ++字符串到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樣式字符串(以null結尾的charcaters / bytes數組)。

您可以使用std::string::data方法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));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM