Last active
December 30, 2015 09:59
-
-
Save GeordieP/7813074 to your computer and use it in GitHub Desktop.
Part 2 of binary conversion assignment
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <iostream> | |
#include <string> | |
#include <cmath> | |
using namespace std; | |
int main(){ | |
cout << "Enter binary: "; | |
string binary; | |
binary = ""; | |
getline(cin,binary); | |
double exponent = 0; | |
double mantissa = 0; | |
int sign = 1; | |
if (binary == "11111111111111111111111111111111"){ | |
cout << "NaN"; | |
} else if (binary == "00000000000000000000000000000000"){ | |
cout << "0"; | |
} else if (binary == "10000000000000000000000000000000"){ | |
cout << "-0"; | |
} else if (binary == "01111111100000000000000000000000"){ | |
cout << "infinity"; | |
} else if (binary == "11111111100000000000000000000000"){ | |
cout << "-infinity"; | |
} else { | |
for (int i = 0; i < binary.length(); i++){ | |
if (i == 0){ // sign | |
if (binary[i] - '0' == 1) sign = -1; | |
} else if (i > 0 && i < 9){ // exponent | |
exponent += (binary[i] - '0') * pow(2, (8 - i)); | |
} else { // mantissa | |
mantissa += (binary[i] - '0') * pow(2, ((binary.length() - 1) - i)); | |
} | |
} | |
exponent -= 127; | |
mantissa /= pow(2, 23); | |
cout << "decimal: " << sign * (1 + mantissa) * pow(2, exponent) << "\n"; | |
} | |
getchar(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment