将float向量转换为字节向量并返回 [英] Convert float vector to byte vector and back

查看:224
本文介绍了将float向量转换为字节向量并返回的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我试图在float和unsigned char数组之间做一些转换(在这种情况下是std :: vector),并且遇到了一些麻烦。我已经将浮点数向量转换为无符号字符,如下所示...

  vector< float> myFloats; 
myFloats.push_back(1.0f);
myFloats.push_back(2.0f);
myFloats.push_back(3.0f);
$ b $ const unsigned char * bytes = reinterpret_cast< const unsigned char *>(& floats [0]);

vector< unsigned char> byteVec; (int i = 0; i <3; i ++)
byteVec.push_back(bytes [i])的

;

我希望自己做得对,如果不是这样的话部分将无法正常工作。

  //在程序后面的某个地方转换
unsigned char * bytes =&(byteVec [0]); //指向内存的开始
float * floatArray = reinterpret_cast< float *>(* bytes); (int i = 0; i <3; i ++)
cout<< floatArray [i]<< ENDL; //错误在这里

我试过用(字节)代替(* bytes)部分,但打印错误的值。 (int i = 0; i <3; i ++)
cout($ i $)
$ b

  << (float)bytes [i]<< ENDL; 

不知道如何从中取回原始的浮动值。

感谢您的帮助。

解决方案

解决:

我认为问题出在这里

  vector< unsigned char> byteVec; (int i = 0; i <3; i ++)
byteVec.push_back(bytes [i])的

;

我将其删除并替换为

  vector< unsigned char> byteVec(bytes,bytes + sizeof(float)* myFloats.size()); 

然后剩下的就可以正常工作了!

另外,请记住在这里使用(字节)而不是(*字节)

$ $ $ $ $ $ $ $ $ $ $ $ float $ floatArray = reinterpret_cast< float *>(字节);


I'm trying to do some conversions between float and unsigned char arrays (std::vector in this case) and i've run into some troubles.

I've converted the vector of floats to unsigned char like this...

vector<float> myFloats;
myFloats.push_back(1.0f);
myFloats.push_back(2.0f);
myFloats.push_back(3.0f);

const unsigned char* bytes = reinterpret_cast<const unsigned char*>(&floats[0]);

vector<unsigned char> byteVec;

for (int i = 0; i < 3; i++)
    byteVec.push_back(bytes[i]);

I'm hoping i've done this correctly, if not that would be the reason why the next part wont work.

// converting back somewhere later in the program
unsigned char* bytes = &(byteVec[0]);    // point to beginning of memory
float* floatArray = reinterpret_cast<float*>(*bytes);

for (int i = 0; i < 3; i++)
    cout << floatArray[i] << endl;  // error here

I've tried using (bytes) instead of (*bytes) in that last part but that prints the wrong values. Doing this also printed the wrong values

for (int i = 0; i < 3; i++)
    cout << (float)bytes[i] << endl;

Not sure how to get my original float values back from this.

Thanks for any help.

解决方案

Solved:

I think the problem was here

vector<unsigned char> byteVec;

for (int i = 0; i < 3; i++)
    byteVec.push_back(bytes[i]);

I removed that and replaced it with

vector<unsigned char> byteVec(bytes, bytes + sizeof(float) * myFloats.size());

then the rest works fine!

Also, remember to use (bytes) instead of (*bytes) here

float* floatArray = reinterpret_cast<float*>(bytes);

这篇关于将float向量转换为字节向量并返回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆