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.运行结果