Changing Binary to Morse code

I'm trying to convert my code from binary to morse code. So what I want to do is read two bits at a time then use the key I've created to change the zeros and ones to dashes and dots.
vector<std::bitset<8>> vec_b8
{
bitset<8>("01010110"),
bitset<8>("01010111"),
bitset<8>("01011000")
};
vector<std::bitset<2>> vec_b2;
bitset<2> b2;
for(auto b8 : vec_b8)
{
for(size_t i = b8.size() - 2; i > 0; --i) {

b2[0] = b8[i];
b2[1] = b8[i+1];
vec_b2.emplace_back(b2);
}
if (b2[0] == 00)//Letter space
{
cout<<" ";
}
else if( b2[0] == 01)//Dash
{
cout<<"-";
}
else if(b2[0] <= 10)//Dot
{
cout<<".";
}
else if(b2[0] <= 11)//Word space
{
cout<<" ";
}
else
{
cout<<"Error has occured"<<endl;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <iostream>
#include <vector>
#include <bitset>
using namespace std;

int main() {
    vector<bitset<8>> vec_b8 {
        bitset<8>("01010110"),
        bitset<8>("01010111"),
        bitset<8>("01011000")
    };
    for(auto b8 : vec_b8) {
        for(size_t i = b8.size(); i > 0; i -= 2) {
            int x = b8[i - 1] * 2 + b8[i - 2];
            if (x == 0)      //Letter space
                cout << ' ';
            else if (x == 1) //Dash
                cout << '-';
            else if (x == 2) //Dot
                cout << '.';
            else if (x == 3) //Word space
                cout << "  ";
        }
    }
    cout << '\n';
}

@tpb How did you read the two bits at a time? Can you explain how you did the conversion so I can understand better? Thanks for your help by the way.
i is going through the sequence 8, 6, 4, 2.

b8 is indexed by i-1 and i-2 to get the bit pair. So those index pairs go through the sequence (7,6), (5,4), (3,2), (1,0).

Each bit pair is translated into its numerical value, 0 to 3 (the higher bit has a value of 2, so it's multiplied by 2).

Note that the bits are indexed oppositely to how the string characters are indexed. The lowest-order bit becomes array element 0.

1
2
3
4
bitset<8>("01010110")
// gives this array of bits:
// 0 1 2 3 4 5 6 7
// 0,1,1,0,1,0,1,0 

Last edited on
Topic archived. No new replies allowed.