首页主机资讯如何在C++中实现bytearray的序列化

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

时间2024-08-15 16:08:03发布访客分类主机资讯浏览1535
导读:在C++中实现bytearray的序列化可以通过使用std::vector来实现。下面是一个简单的示例: #include <iostream> #include <vector> #include <fstr...

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

声明:本文内容由网友自发贡献,本站不承担相应法律责任。对本内容有异议或投诉,请联系2913721942#qq.com核实处理,我们将尽快回复您,谢谢合作!


若转载请注明出处: 如何在C++中实现bytearray的序列化
本文地址: https://pptw.com/jishu/694113.html
C++中bytearray与其他数据结构的比较 Linux中bcache的日志和调试信息

游客 回复需填写必要信息