C++ vector 中 double 与 int8_t 转化

1. vector<double> 转化为 vector<int8_t>

void EncodeDouble(const std::vector<double>& data, std::vector<int8_t>& result)
{
    const double *dataPtr = data.data();
    uint32_t dataSize = data.size() * sizeof(double);
    std::size_t    current = 0;

    while (current + sizeof(int8_t) <= dataSize)
    {
        int8_t val;
        memcpy(&val, (uint8_t*)dataPtr + current, sizeof(val));
        current += sizeof(val);
        result.push_back(val);
    }
}

2. vector<int8_t> 转化为 vector<double>

void DecodeToDouble(const std::vector<int8_t>& data, std::vector<double>& result)
{
    const int8_t *dataPtr = data.data();
    uint32_t dataSize = data.size() * sizeof(int8_t);
    std::size_t    current = 0;

    while (current + sizeof(double) <= dataSize)
    {
        double val;
        memcpy(&val, (uint8_t*)dataPtr + current, sizeof(val));
        current += sizeof(val);
        result.push_back(val);
    }
}

3.测试

#include <iostream>
#include <vector>

int main()
{
    std::vector<double> data = { 1.2, 4.5, 10.0, 12.3 };

    std::vector<int8_t> encodeData;
    EncodeDouble(data, encodeData);

    std::vector<double> decodeData;
    DecodeToDouble(encodeData, decodeData);
    for (auto iter = decodeData.begin(); iter != decodeData.end(); iter++)
    {
        std::cout << *iter << " ";
    }
    std::cout << std::endl;

    getchar();
    return 0;
}

4.运行结果

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值