-
Notifications
You must be signed in to change notification settings - Fork 0
/
decimal2binary_float.cpp
65 lines (59 loc) · 1.46 KB
/
decimal2binary_float.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <string>
#include <vector>
int IntVal(const float& var) {
return ((int) var);
}
float FloatVal(const float& var) {
return (var - IntVal(var));
}
std::string IntBinary(const float& var) {
int intValue = IntVal(var);
std::string result = "0x";
std::string bit;
std::vector<std::string> digitContainer;
while (intValue > 0) {
bit = std::to_string(intValue % 2);
digitContainer.push_back(bit);
intValue /= 2;
}
for (std::vector<std::string>::iterator it = digitContainer.end() -1;
it >= digitContainer.begin(); it--) {
result += *it;
}
return result;
}
std::string FloatBinary(const float& var) {
float floatValue = FloatVal(var);
// 10 digits at most;
int precision = 10;
int intValue;
std::string result = ".";
std::string bit;
std::vector<std::string> digitContainer;
while (precision) {
if (floatValue == 0) {
break;
} else {
intValue = IntVal(floatValue * 2);
bit = std::to_string(intValue);
digitContainer.push_back(bit);
floatValue = floatValue * 2 - intValue;
precision--;
}
}
for (std::vector<std::string>::iterator it = digitContainer.end() -1;
it >= digitContainer.begin(); it--) {
result += *it;
}
return result;
}
std::string Decimal2Binary (const float& var) {
return IntBinary(var) + FloatBinary(var);
}
int main() {
std::cout << Decimal2Binary(4.0121) << std::endl;
return 0;
}