将浮点向量转换为 hex/binary 字符串

Converting vector of floats to hex/binary string

根据 this answer about encoding/decoding to base 64, and this 关于从浮点向量转换为字节向量并返回的回答,我试图将浮点向量转换为十六进制或二进制字符串。

这是我的代码:

vector<float> floats = ...;
const unsigned char* bytes = reinterpret_cast<const unsigned char*>(&floats[0]);
std::vector<unsigned char> byteVec(bytes, bytes + sizeof(float) * floats.size());
std::cout<<byteVec.size()<<std::endl;
std::string dat = base64_encode(&byteVec[0], byteVec.size());
std::vector<unsigned char> decodedData = base64_decode(dat);
std::cout<<decodedData.size()<<std::endl;
unsigned char* bytesN = &(decodedData[0]);    // point to beginning of memory
float* floatArray = reinterpret_cast<float*>(bytesN);
std::vector<float> floatVec(floatArray, floatArray + sizeof(unsigned char) * decodedData.size());   
std::cout<<floatVec.size()<<std::endl;

原始向量floats是262,144个floats,两个cout语句打印1048576,然后程序出现段错误。我做错了什么?

此外,是否有更好或更快的方法来完成此操作?我想使用 xml/gsoap 发送字符串,所以如果 gsoap 有自动执行此操作的功能,它会让我的生活更轻松。

一个主要问题是:

std::vector<float> floatVec(floatArray, floatArray + sizeof(unsigned char) * decodedData.size());

这里你说元素个数是decodedData.size(),也就是1048576。但这是错误的,因为它应该只是它的四分之一(因为 decodedData.size() 字节 的大小而不是 float 元素的数量)。这当然会导致超出 decodedData 的范围,从而导致 未定义的行为

您需要将 decodedData.size() 的大小除以 sizeof(float):

std::vector<float> floatVec(floatArray, floatArray + decodedData.size() / sizeof(float));