In: Computer Science
I'm trying to convert between different number representations in C++ , I have the prototype but im not sure what do do from here
bool convertF(double & x, const string & bits);
bits is supposed to be an 8-bit (not 5-bit) value, each char being '0' or '1'; if not, return
false. The first bit of bits represents the sign bit, the next 3 bits represent the exponent,
and the next 4 bits represent the significand.
convertF may assume without checking that the 3 exponent bits are not all the same.
convertF's job is to set x to the floating-point number that bits represents and return
true.
For example, convertF(x, "101011000") should set x to -7/8 == -0.875
double helper(double a){
string aString = to_string(a);
int decimalPlace=aString.length();
for(int i=0;i<aString.length();i++){
if(aString[i]=='.'){
decimalPlace =
i;
break;
}
}
double ans = 0;
double p = 1;
for(int i=decimalPlace-1;i>=0;i--){
if(aString[i]=='1')
ans+=p;
p = p*2;
}
p = 0.5;
for(int
i=decimalPlace+1;i<aString.length();i++){
if(aString[i]=='1')
ans+=p;
p = p/2.0;
}
return ans;
}
bool convertF(double &x, const string & bits){
if(bits.length()==8){
for(int i=0;i<8;i++){
if(bits[i]=='0'
|| bits[i]=='1')continue;
else return
false;
}
bool isPositive = true;
if(bits[0]==1)isPositive =
false;
string exponent =
bits[1]+bits[2]+bits[3];
int valExp =
binaryOf(exponent)-3;
double mantissa = 0.0;
if(bits[4]){
mantissa+=0.1;
}
if(bits[5]){
mantissa+=0.01;
}
if(bits[6]){
mantissa+=0.001;
}
if(bits[7]){
mantissa+=0.0001;
}
double val = 1.0;
val+=mantissa;
val = val*power(10,valExp);
x = helper(val);
if(!isPositive)x =
x*(-1);
return true;
}
return false;
}
The above is a complete implementation for given an 8 bit floating point representation , to find the floating point number . In the above code , two functions have been considered that they can be easily computed namely binaryOf() which takes in as input a string and finds the corresponding decimal value , and power() which calculates x^y even when y is negative.These two functions can be easily implemented but if difficulty is encountered,then do comment.