从文件中读取ascii字符,然后将其转换为一个位字符串c++

reading in ascii characters from a file and then turning them into a bit string c++

本文关键字:一个 c++ 字符串 转换 读取 文件 ascii 字符 然后      更新时间:2023-10-16

所以我在一个文件上有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;
  }
}