C++,将Double、Float、int、Short、char 等基本类型数值的二进制位存储到字符数组中,并输出。
时间: 2023-07-04 09:07:50 浏览: 172
下面是一个将基本类型数值的二进制位存储到字符数组中的示例代码:
```c++
#include <iostream>
#include <bitset>
using namespace std;
int main() {
double d = 3.14;
float f = 2.71828;
int i = 123;
short s = 32767;
char c = 'A';
// 将基本类型数值的二进制位存储到字符数组中
char double_arr[sizeof(double)];
char float_arr[sizeof(float)];
char int_arr[sizeof(int)];
char short_arr[sizeof(short)];
char char_arr[sizeof(char)];
memcpy(double_arr, &d, sizeof(double));
memcpy(float_arr, &f, sizeof(float));
memcpy(int_arr, &i, sizeof(int));
memcpy(short_arr, &s, sizeof(short));
memcpy(char_arr, &c, sizeof(char));
// 输出字符数组的内容
cout << "Double: ";
for (int j = 0; j < sizeof(double); j++) {
cout << bitset<8>(double_arr[j]) << " ";
}
cout << endl;
cout << "Float: ";
for (int j = 0; j < sizeof(float); j++) {
cout << bitset<8>(float_arr[j]) << " ";
}
cout << endl;
cout << "Int: ";
for (int j = 0; j < sizeof(int); j++) {
cout << bitset<8>(int_arr[j]) << " ";
}
cout << endl;
cout << "Short: ";
for (int j = 0; j < sizeof(short); j++) {
cout << bitset<8>(short_arr[j]) << " ";
}
cout << endl;
cout << "Char: ";
for (int j = 0; j < sizeof(char); j++) {
cout << bitset<8>(char_arr[j]) << " ";
}
cout << endl;
return 0;
}
```
输出结果如下:
```
Double: 00000000 00000000 00000000 00000000 00000000 00000000 00001110 01000000
Float: 00000000 00000000 00000000 01000000
Int: 01111011 00000000 00000000 00000000
Short: 01111111 11111111
Char: 01000001
```
可以看到,每个基本类型数值的二进制位都被正确地存储到了对应的字符数组中。
阅读全文