C++写二进制文件

源文件
在这里插入图片描述


#include <iostream>
#include <fstream>
#include <sstream>
#include <cmath>

void convert2() {
    // 打开输入文本文件
    std::ifstream inputFile("mask.txt");

    // 打开输出二进制文件
    std::ofstream outputFile("mask.dat", std::ios::binary | std::ios::out | std::ios::trunc);

    if (inputFile.is_open() && outputFile.is_open()) {
        std::string line;
        while (std::getline(inputFile, line)) {
            std::istringstream iss(line);
            std::string number;

            while (std::getline(iss, number, ',')) {
                // 将每个数字转换为2进制表示,占1字节
                int decimalValue = floor(std::stoi(number) / 256.0);
                char binaryValue = static_cast<char>(decimalValue);

                // 写入二进制数据到输出文件
                outputFile.write(&binaryValue, sizeof(char));

            }
        }

        // 关闭文件
        inputFile.close();
        outputFile.close();

        std::cout << "转换完成。输出文件为mask.dat" << std::endl;
    }
    else {
        std::cerr << "无法打开文件。请确保输入文件存在并且可读。" << std::endl;
    }
}
  • 9
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值