c++ 如何将获取到的一段2进制文件打印出来
时间: 2023-12-12 17:06:03 浏览: 110
要将获取到的二进制文件打印出来,可以使用C++中的文件输入输出流(`fstream`)来读取二进制文件,并使用`std::hex`或`std::bitset`等方法将其转换为16进制或二进制字符串,然后打印输出即可。
以下是一个将二进制文件转换为16进制字符串并打印输出的示例代码:
```c++
#include <iostream>
#include <fstream>
#include <iomanip>
using namespace std;
int main() {
ifstream input("binary_file.bin", ios::binary); // 以二进制模式读取文件
if (!input.is_open()) {
cout << "Failed to open file!" << endl;
return 1;
}
// 逐个字节读取二进制文件,并将其转换为16进制字符串
char ch;
while (input.get(ch)) {
cout << setfill('0') << setw(2) << hex << static_cast<int>(ch); // 输出16进制字符串
}
input.close();
return 0;
}
```
其中,`setfill`和`setw`函数用于设置输出的宽度和填充字符。`hex`表示16进制输出格式,`static_cast`用于将字符转换为整数。
如果要输出二进制字符串,可以使用`std::bitset`类:
```c++
#include <iostream>
#include <fstream>
#include <bitset>
using namespace std;
int main() {
ifstream input("binary_file.bin", ios::binary);
if (!input.is_open()) {
cout << "Failed to open file!" << endl;
return 1;
}
// 逐个字节读取二进制文件,并将其转换为二进制字符串
char ch;
while (input.get(ch)) {
bitset<8> bits(ch);
cout << bits.to_string(); // 输出二进制字符串
}
input.close();
return 0;
}
```
其中,`bitset<8>`表示每个字符转换为8位二进制字符串。
相关推荐
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)