从文件中读取ascii字符,然后将其转换为一个位字符串c++
reading in ascii characters from a file and then turning them into a bit string c++
所以我在一个文件上有ascii字符ÅT,我试图将它们转换回二进制字符串(所以它应该返回的二进制字符串分别是:"11100011"、"11000101"、"01010100")。如何读取无符号字符(字节),然后将其转换为位字符串?任何详细的教程链接和/或建议都会有所帮助!非常感谢。
---编辑-----
这是我正在玩的一些代码,它获得了我提到的字符(这是我问的关于c++比特串到字节的问题的一部分)。
#include <iostream>
#include <fstream>
#include <iomanip>
#include <string>
#include <bitset>
#include <vector>
#include <stdio.h>
using namespace std;
void main(){
ofstream outf;
outf.open("test.outf", std::ofstream::binary);
ifstream inf;
//given string of 1's and 0's, broke them down into substr
//of 8 and then used a bitset to convert them to a byte
//character on the output file
string bitstring = "11100011110001010101010";
unsigned char byte = 0;
cout << bitstring.length() << endl;
for (int i = 0 ; i < bitstring.length(); i += 8){
string stringof8 = "";
if (i + 8 < bitstring.length()){
stringof8 = bitstring.substr(i, 8);
cout << stringof8 << endl;
}
else
stringof8 = bitstring.substr(i);
if (stringof8.size() < 8){
stringof8 += "0";
cout << stringof8 << endl;
}
bitset<8> b(stringof8);
byte = (b.to_ulong()&0xFF);
outf.put(byte);
}
cout << endl;
system("pause");
}
我试图取回比特串。当我看到notepad++的二进制模式时,它显示相同的二进制字符串(如果我把它们分成8块)。
您可以一点一点地转换它。另一种方法是将十进制数转换为二进制数
更新:
string convert(unsigned char c){
string bitstr(8,'0');
int n = 7;
while(n >= 0){
bitstr[7-n] = (c >> n) & 1 ? '1' : '0';
--n;
}
return bitstr;
}
string convert10To2(unsigned char c){
string bitstr = "";
int val = c;
int base = 128;
int n = 8;
while(n-- > 0){
bitstr.append(1, (val/base + '0'));
val %= base;
base /= 2;
}
return bitstr;
}
int main() {
ofstream out;
out.open("data.txt");
char ccc = (char)227;
out << ccc;
out.close();
ifstream in;
in.open("data.txt");
int ival = in.get();
char c = ival;
cout<<convert(c)<<endl; //output: 11100011
cout<<convert10To2(c)<<endl; //output: 11100011
return 0;
}
只需将字符存储在一个字符数组中,并使用类似的位集函数。
#include <bitset>
char bbb[3] = {'b', 'f', 't'};
for (std::size_t i = 0; i < 3; ++i)
{
cout << bitset<8>(bbb[i]) << endl;
}
}
相关文章:
- 如何创建一个CMake变量,除非显式重写,否则使用默认值
- 删除一个线程上有数百万个字符串的大型哈希映射会影响另一个线程的性能
- 为什么两个不同的未命名名称空间可以共存于一个cpp文件中
- 运行同一解决方案的另一个项目的项目
- 挂起和取消挂起一个文件DLL
- 用C++中的一个变量定义一个常量
- 函数向量_指针有不同的原型,我可以构建一个吗
- 在c++中用vector填充一个简单的动态数组
- 如何在选项卡视图Qt中设置一个新项目,并保存以前的项目
- 预处理器:插入结构名称中的前一个行号
- 我在c++代码中生成了一个运行时#3异常
- 我想将一个对T类型的非常量左值引用绑定到一个T类型的临时值
- 从链接列表c++中删除一个项目
- 告诉一个 const char 数组,除了编译时 C 样式的字符串外,它不以 '