Search code examples
c++ifstream

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


So i have ascii characters ãÅT on a file and I was trying to convert them back to a binary string (so the binary strings it should give back are (respectively): "11100011", "11000101", "01010100"). How would you read in unsigned char (bytes) and then convert them to a bitstring? Any detailed tutorial links and/or advice would help! Thank you!

---edit -----

so here is some code I'm playing with that gets the characters I was mentioning (part of a question I asked on 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");
}

i tried to get the bitstring back. When I look at the binary mode of notepad++ , it shows the same binary strings (if i broke them up into 8 pieces).


Solution

  • You can convert it bit by bit. Another approach is converting decimal number to binary number.
    Updated:

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