在C++中實現bytearray的序列化可以通過使用std::vector來實現。下面是一個簡單的示例:
#include <iostream>
#include <vector>
#include <fstream>
void serializeByteArray(std::vector<char> byteArray, const std::string& filename) {
std::ofstream file(filename, std::ios::out | std::ios::binary);
if (!file) {
std::cerr << "Error opening file" << std::endl;
return;
}
file.write(byteArray.data(), byteArray.size());
file.close();
}
std::vector<char> deserializeByteArray(const std::string& filename) {
std::vector<char> byteArray;
std::ifstream file(filename, std::ios::in | std::ios::binary);
if (!file) {
std::cerr << "Error opening file" << std::endl;
return byteArray;
}
file.seekg(0, std::ios::end);
int fileSize = file.tellg();
file.seekg(0, std::ios::beg);
byteArray.resize(fileSize);
file.read(byteArray.data(), fileSize);
file.close();
return byteArray;
}
int main() {
std::vector<char> originalByteArray = {0x01, 0x02, 0x03, 0x04, 0x05};
serializeByteArray(originalByteArray, "serialized.dat");
std::vector<char> deserializedByteArray = deserializeByteArray("serialized.dat");
for (char byte : deserializedByteArray) {
std::cout << std::hex << (int)byte << " ";
}
std::cout << std::endl;
return 0;
}
在上面的示例中,serializeByteArray函數將傳入的byteArray寫入到一個二進制文件中,而deserializeByteArray函數從文件中讀取byteArray并返回。在main函數中,我們首先序列化一個包含一些字節的byteArray,然后反序列化并打印出來。