Hello,
Based on this thread :
Read string convert and write
I wrote the code below. It reads floating point numbers from a test file, converts them to a fixed point integer and writes them to another file.
The code seems to work - but I'd like to get your feedback about it.
Do you see any weak spots ? What would you change ? Style ? Anything...
Code:
#include <iostream>
#include <fstream>
#include <cmath>
using namespace std ;
/*
This function converts a floating point number to a signed integer fixed point representation.
Selecting whether to treat the input as signed or unsigned is done using the "sign" boolean.
The integer bits "budget" can be configured using the number_integer_bits argument.
The fraction bits "budget" can be configured using the number_fraction_bits argument.
*/
unsigned int double_to_fixed ( bool sign , unsigned int number_integer_bits , unsigned int number_fraction_bits , double number )
{
double absolute_number = abs ( number ) ; // Get the absolute value for the number.
double fraction_absolute_number = absolute_number - int ( absolute_number ) ; // Decrement the integer portion to be left only with the fraction.
unsigned int accumulator = 0 ; // The accumulator will be used to calculate the integer portion.
unsigned int result ; // The accumulator will be used to calculate the integer portion.
for ( int index = number_integer_bits - 1 ; index >= 0 ; index -- )
{
if ( accumulator + pow ( 2 , index ) <= absolute_number ) // Checking if we should include the current index in the result.
{
accumulator = accumulator + pow ( 2 , index ) ;
}
}
unsigned int scaled_fraction_absolute_number = int ( fraction_absolute_number * pow ( 2 , number_fraction_bits ) ) ;
unsigned int scaled_integer_absolute_number = accumulator * pow ( 2 , number_fraction_bits ) ;
unsigned int integer_plus_fraction = scaled_integer_absolute_number + scaled_fraction_absolute_number ;
if ( sign == 1 ) // Treat the number as signed
{
unsigned int all_ones = pow ( 2 , 1 + number_integer_bits + number_fraction_bits ) - 1 ; // 1 + is for the extra sign bit.
result = all_ones - integer_plus_fraction + 1 ; // 2's complement to get the negative value.
}
else // Treat the number as unsigned
{
result = integer_plus_fraction ;
}
// cout << int ( result ) << endl ; // For Debug purposes.
return result ;
}
int main ( )
{
ifstream file_in ( "file_in.txt" ) ;
ofstream file_out ( "file_out.txt" ) ;
double number ;
/*
The function arguments:
1 - Treat the input as signed.
10 - The integer bits budget is 10 bits.
16 - The fraction bits budget is 16 bits.
*/
while ( file_in >> number )
{
file_out << double_to_fixed ( 1 , 10 , 16 , number ) << '\n' ;
}
return 0 ;
}