Write a C++ program called that reads in a floating point number and outputs its
ID: 3784827 • Letter: W
Question
Write a C++ program called that reads in a floating point number and outputs its
scientific base 2 format.
1. Example 1:
Please enter a float: 3.75
1.111E1
2. Example 2:
Please enter a float: 140.1
1.0001100000110011001101E7
• You should use bitwise operators to pick out the fields that you need to work with.
• In order to do the appropriate bitwise operations on the float it must first be cast to an int but
(int) f (assuming f is the variable you have stored you float in) will not work as the cast will
convert the float representation to the 2's compliment integer representation. The fix is to take
the address of the float, cast it as an unsigned int*, and then dereference
unsigned int float_int = *((unsigned int*)&f);
Explanation / Answer
#include <iostream>
// declaring union
typedef union {
float f;
unsigned int ui;
unsigned char c[4];
} Fl_u;
// this function used to convert floating point number to scientific base 2 format
void fbinprint(float f){
Fl_u x;
unsigned wk=0;
x.f = f;
wk = x.ui;
if(wk & 0x80000000)
std::cout << '-';
unsigned bit = wk & 0x07FFFFF;
std::cout << "1.";
for(int i = 0; i< 23 ; ++i){
bit <<=1;
std::cout << (bit & 0x0800000 ? '1' : '0');
}
std::cout << " E";
int exp = (wk >> 23) & 0x0FF;
exp -= 127;//bias 127
if(exp < 0){
std::cout << '-';
exp = -exp;
}
int i = 0;
while((exp & 0x080) == 0 && i < 8){
exp <<= 1;
++i;
}
if(i == 8)
std::cout << '0';
for(;i< 8 ; ++i){
std::cout << (exp & 0x080 ? '1' : '0');
exp <<=1;
}
std::cout << std::endl;
}
int main(){
/* I am using here the custom input baased on question rquirement.
i hope you C++ code to get runtime input*/
float f = 3.75;
std::cout << "Please enter a float: " << f << std::endl;
std::cout << "Output: ";
fbinprint(f);
std::cout << std::endl;
f = 140.1;
std::cout << "Please enter a float: " << f << std::endl;
std::cout << "Output: ";
fbinprint(f);
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.