Given float numbers of precision 3 (rounded to decimal places), e.g. 0.123. Following method can de/serialize float numbers safely across platforms of different endianness.
// Serialization
float number[100];
std::ofstream fout(“output”);
for(int i=0;i<100;++i)
fout<< (number*1000) <<endl;
// De-serialization
int value;
float result[100];
std::ifstream fin(“input”);
for(int i=0;i<100;++i){
fin>>value;
result[i] = value/1000.0;
}
By translating float number to a discrete form, the cost of de/serialization (text to double) is reduced since it becomes a text to integer conversion.
- Original posted in my Tumblr
Update: Another technique
union {
int ival;
float fval;
} number;
number.fval = 0.1234;
fout << number.ival;
fout >> number.ival;
// use number.fval
– Written with StackEdit.
留言
張貼留言