Search code examples
c++binaryasciibitset

from ascii to bits but not working the contrary


I got stuck in this problem.

I'm writing a c++ program in which:

1- you write a 6 chars string

2- that string is converted into bits (let's call this 'A')

3- this string of bits is copied in another string and reverted via reverse() method (let's call this 'B')

4- a bitwise OR is executed between A and B (let's call this result 'C')

5- (here's where i got stuck) C should be converted into ASCII.... but i'ts not. I get in output strange symbols/question marks.

Here's the code:

#include <iostream>
#include <bitset>
#include <sstream>
#include <string>
#include <algorithm>
using namespace std;

int main()
{

    // PART ONE: from string to bits
    string input;
    cout << "Insert the 6 letters string you want to convert: \n";
    do
    {
        getline(cin, input);
        if (input.length() < 6 || input.length() > 6)
        {
            cout << "\nIt must be 6 letters!\n";
        }
    } while (input.length() != 6);

    string inbits;
    bitset<8> newbits;
    for (size_t i = 0; i < input.size(); ++i)
    {
        newbits = bitset<8>(input.c_str()[i]);
        string aux = newbits.to_string<char, std::string::traits_type, std::string::allocator_type>();
        inbits.append(aux);
    }
    cout << endl << inbits << endl;

    // PART TWO: bitwise or
    string inverted = inbits;
    reverse(inverted.begin(), inverted.end());
    bitset<48> bstr1(inbits), bstr2(inverted), finale;
    finale = bstr1 | bstr2; // here it is done the bitwise OR
    cout << finale << endl;
    string ored = finale.to_string<char, std::string::traits_type, std::string::allocator_type>();

    // PART THREE: from bits to string of char
    stringstream sstream(ored);
    string aux = "";
    while (sstream.good())
    {
        bitset<8> bits;
        sstream >> bits;
        char c = char(bits.to_ulong());
        aux += c;
    }
    cout << "the ored string is: " << aux << endl;
}

I don't know what goes wrong. I mean, it could be a sort of """overflow""" but it just doesn't make any sense. How should i proceed?

(Sorry for my bad english, this is the first time I open a thread here, I'm kind of unsure on how to move here)


Solution

  • If your results dont fall into the range 0x41 to 0x5A you wont get a alphabetical result: Link to the ascii table site