从文件中读取ascii字符,然后将它们转换为字符串c ++

时间:2014-11-10 07:40:51

标签: c++ ifstream

所以我在文件上有ascii字符ãÅT,我试图将它们转换回二进制字符串(所以它应该返回的二进制字符串分别是:“11100011”,“11000101”,“01010100”) 。你会如何读取unsigned char(bytes)然后将它们转换为bitstring?任何详细的教程链接和/或建议都会有所帮助!谢谢!

---编辑-----

所以这里有一些我正在玩的代码可以获得我提到的字符(我在c++ bitstring to byte上提出的问题的一部分)。

#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个部分)。

2 个答案:

答案 0 :(得分:0)

只需将字符存储在字符数组中,然后使用bitset函数。

#include <bitset>

char bbb[3] = {'b', 'f', 't'};
for (std::size_t i = 0; i < 3; ++i)
  {
      cout << bitset<8>(bbb[i]) << endl;
  }
}

答案 1 :(得分:0)

你可以一点一点地转换它。另一种方法是将十进制数转换为二进制数 更新:

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;
}