c++

如何在C++中实现bytearray的序列化

小樊
82
2024-08-15 11:21:38
栏目: 编程语言

在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,然后反序列化并打印出来。

0
看了该问题的人还看了