I want to know how to convert values of float and double into binary format and push into vector of type uint8_t
Eg : float x = 23.22;
double z = 2.32232;
and store them into vector while serializing
vector<uint8_t> data.
and also convert back into original value while deserializing.
Is there any way to do this?
CodePudding user response:
If you just need to push them into vector and pop them (like a stack) you can do this:
void push( std::vector<uint8_t> &v, float f )
{
auto offs = v.size();
v.resize( offs sizeof( float ) );
std::memcpy( v.data() offs, &float, sizeof( float ) );
}
float popFloat( std::vector<uint8_t> &v )
{
float f = 0;
if( v.size() >= sizeof( float ) ) {
auto offs = v.size() - sizeof( float );
std::memcpy( &f, v.data() offs, sizeof( float ) );
v.resize( offs );
}
return f;
}
Note this would store them in not portable format, but should work for storing/reading them to/from file on the same hardware.
You may rewrite those 2 functions as template and it will work with all integral and floating point types ( short
int
long
double
etc )