mercredi 19 septembre 2018

convert (n first bytes of) unsigned char pointer to float and double c++

Consider the following c++ code:

unsigned char* data = readData(..);        //Let say data consist of 12 characters
unsigned int dataSize = getDataSize(...);  //the size in byte of the data is also known (let say 12 bytes)

struct Position 
{
   float pos_x;    //remember that float is 4 bytes
   double pos_y;   //remember that double is 8 bytes
}

Now I want to fill a Position variable/instance with data.

Position pos;
pos.pos_x = ?   //data[0:4[ The first 4 bytes of data should be set to pos_x, since pos_x is of type float which is 4 bytes
pos.pos_x = ?   //data[4:12[ The remaining 8 bytes of data should be set to pos_y which is of type double (8 bytes)

I know that in data, the first bytes correspond to pos_x and the rest to pos_y. That means the 4 first byte/character of data should be used to fill pos_x and the 8 remaining byte fill pos_y but I don't know how to do that. Any idea? Thanks. Ps: I'm limited to c++11

Aucun commentaire:

Enregistrer un commentaire