用c++1.编写无符号数的转换: unsigned int unsignedToValue(char binary[],int n); 要求在main中从屏幕读入n个二进制数即0或者是1,调用unsignedToValue函数返 回此二进制数代表的无符号数的真值。 2.编写有符号数的转换: int intToValue(char binary[],int n); 要求在main中从屏幕读入n个二进制数即0或者是1,调用intToValue函数返回此 二进制数代表的有符号数的真值。 3.编写单精度浮点数的转换 float floatToValue(char binary[]); 要求在main中从屏幕读入32个二进制数即0或者是1,调用intToValue函数返回此 二进制数代表的浮点数的真值,要求能够输出非规格化数:无穷大,0,非数。
时间: 2024-03-20 07:45:34 浏览: 65
1. 无符号数的转换
```c++
#include <iostream>
#include <cmath>
using namespace std;
unsigned int unsignedToValue(char binary[], int n) {
unsigned int result = 0;
for (int i = 0; i < n; i++) {
result += pow(2, n - i - 1) * (binary[i] - '0');
}
return result;
}
int main() {
int n;
cin >> n;
char binary[n];
for (int i = 0; i < n; i++) {
cin >> binary[i];
}
unsigned int result = unsignedToValue(binary, n);
cout << result << endl;
return 0;
}
```
2. 有符号数的转换
```c++
#include <iostream>
#include <cmath>
using namespace std;
int intToValue(char binary[], int n) {
int result = 0;
int sign = 1;
if (binary[0] == '1') {
sign = -1;
for (int i = 0; i < n; i++) {
binary[i] = (binary[i] == '0') ? '1' : '0';
}
binary[0] = '0';
}
for (int i = 0; i < n; i++) {
result += pow(2, n - i - 1) * (binary[i] - '0');
}
return sign * result;
}
int main() {
int n;
cin >> n;
char binary[n];
for (int i = 0; i < n; i++) {
cin >> binary[i];
}
int result = intToValue(binary, n);
cout << result << endl;
return 0;
}
```
3. 单精度浮点数的转换
```c++
#include <iostream>
#include <bitset>
#include <cmath>
using namespace std;
float floatToValue(char binary[]) {
bitset<32> bits(binary);
int sign = bits[31];
int exponent = 0;
for (int i = 30, j = 0; i >= 23; i--, j++) {
exponent += bits[i] * pow(2, j);
}
int fraction = 0;
for (int i = 22, j = -1; i >= 0; i--, j--) {
fraction += bits[i] * pow(2, j);
}
float result = 0;
if (exponent == 0 && fraction == 0) {
result = (sign == 1) ? -0.0 : 0.0;
} else if (exponent == 255 && fraction == 0) {
result = (sign == 1) ? -INFINITY : INFINITY;
} else if (exponent == 255 && fraction != 0) {
result = NAN;
} else {
exponent -= 127;
result = pow(-1, sign) * (1 + fraction / pow(2, 23)) * pow(2, exponent);
}
return result;
}
int main() {
char binary[32];
for (int i = 0; i < 32; i++) {
cin >> binary[i];
}
float result = floatToValue(binary);
cout << result << endl;
return 0;
}
```
阅读全文