在C ++中将二进制字符串输出到二进制文件 [英] Outputting a Binary String to a Binary File in C++

查看:83
本文介绍了在C ++中将二进制字符串输出到二进制文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

比方说,我有一个包含这样的二进制文件的字符串"0110110101011110110110010010000010".是否有一种简单的方法将该字符串输出到二进制文件中,以便该文件包含0110110101011110110110010010000010?我知道计算机一次写入一个字节,但是我想不出一种将字符串内容作为二进制文件写入二进制文件的方法.

Let's say I have a string that contains a binary like this one "0110110101011110110010010000010". Is there a easy way to output that string into a binary file so that the file contains 0110110101011110110010010000010? I understand that the computer writes one byte at a time but I am having trouble coming up with a way to write the contents of the string as a binary to a binary file.

推荐答案

使用位集:

//Added extra leading zero to make 32-bit.
std::bitset<32> b("00110110101011110110010010000010");

auto ull = b.to_ullong();

std::ofstream f;
f.open("test_file.dat", std::ios_base::out | std::ios_base::binary);
f.write(reinterpret_cast<char*>(&ull), sizeof(ull));
f.close();

这篇关于在C ++中将二进制字符串输出到二进制文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆