【发布时间】:2012-06-13 19:35:25
【问题描述】:
我正在尝试在 float 和 unsigned char 数组(在本例中为 std::vector)之间进行一些转换,但遇到了一些麻烦。
我已经像这样将浮点向量转换为无符号字符...
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]);
我希望我已经正确地完成了这件事,否则这将是下一部分无法工作的原因。
// 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
我尝试在最后一部分中使用 (bytes) 而不是 (*bytes) ,但打印出错误的值。这样做也会打印错误的值
for (int i = 0; i < 3; i++)
cout << (float)bytes[i] << endl;
不知道如何从这里取回我原来的浮点值。
感谢您的帮助。
【问题讨论】:
-
reinterpret_cast<float*>(bytes);(注意括号内没有星号)。 -
我已经在我的帖子中说过我已经尝试过了。我使用(字节)打印出来的第一个值是-2.1267e+037。也许它的常量?
标签: c++ floating-point byte