4

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.

mskfisher
  • 3,291
  • 4
  • 35
  • 48
rocklobster
  • 609
  • 2
  • 10
  • 23

2 Answers2

5

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);
rocklobster
  • 609
  • 2
  • 10
  • 23
2

I have had to do this kind of thing for sending raw byte data over TCP. I used a struct that contains a single unsigned char[4] array and use memcpy to copy the bytes in my float values to the start of this array. It may not be ideal but it does work well enough for my purposes. Obviously you can do the reverse to retrieve the data.

mathematician1975
  • 21,161
  • 6
  • 59
  • 101
  • can i use memcpy for a large array of bytes to a large array of floats? Not sure if it would be efficient to do one at a time. – rocklobster Jun 13 '12 at 19:45
  • 4
    Instead of hard-coding the number 4, you should use `sizeof(float)` to be exact. – Attila Jun 13 '12 at 19:50
  • 2
    Yes you are quite right. The reality is I create unsigned char arrays to store mixed data types - I just used 4 to illustrate the general idea. – mathematician1975 Jun 13 '12 at 19:54