0

I have int arrays of 1s and 0s like-

01101000
01100101
01101100
01101100
01101111

which is bit conversion of "hello". I want to convert it back to character array like-

01101000 -> h
01100101 -> e
01101100 -> l
01101100 -> l
01101111 -> o

can you guys give C++ code snippet for the same ?

Shardul
  • 984
  • 1
  • 12
  • 19

3 Answers3

5

You could define a function like:

char bitsToChar(const char *bits)
{
    char result = 0;
    for (int i = 0; i < 8; i++)
    {
        result = (result << 1) | bits[i];
    }
    return result;
}

In each loop, the next bit is appended to the right of the stored result, "pushing" the previously added bits to the left.

So this code:

#include <iostream>
using namespace std;

char bits[5][8] = {
    {0,1,1,0,1,0,0,0},
    {0,1,1,0,0,1,0,1},
    {0,1,1,0,1,1,0,0},
    {0,1,1,0,1,1,0,0},
    {0,1,1,0,1,1,1,1} };

char bitsToChar(const char *bits)
{
    char result = 0;
    for (int i = 0; i < 8; i++)
    {
        result = (result << 1) | bits[i];
    }
    return result;
}

int main(const char* argv[], const int argc)
{
    for (int j = 0; j < 5; j++)
    {
        for (int i = 0; i < 8; i++)
        {
            cout << (int)bits[j][i];
        }
        cout << " -> " << bitsToChar(bits[j]) << endl;
    }
}

Produces the following output:

01101000 -> h
01100101 -> e
01101100 -> l
01101100 -> l
01101111 -> o
divieira
  • 885
  • 9
  • 17
2

Each int in the array should be left-shifted based on its position in the array (e.g., the rightmost int has its value left-shifted by 0, and the leftmost left-shifted by 7) and then added to a variable that keeps track of the sum. Iterate through the array and keep a sum of the bit-shifted values.

Assuming you're always going to be using arrays of 8 ints:

int bits[8] = {0,1,1,0,1,0,0,0};
char c = 0;
for (int i=0; i<8; i++) {
    c += bits[i]<<(7-i);
}
Walfie
  • 3,376
  • 4
  • 32
  • 38
0

I'll give you a clue, since this appears to be homework.

You can make an int out of binary by conditionally adding as you go through the array. An int can be cast to a char to return a letter.

E.g. in base 3:

10212 : h
21121 : e 
. 
.
.

const int length_of_word = 5;
const int length_of_letter = 5;

char* word = new char[length_of_word];
for (int letter = 0; letter < length_of_word; letter ++)
{
  int accumulator = 0;
  for (int trinaryIndex = 0; trinaryIndex < length_of_letter; trinaryIndex ++)
  {
    int curVal = 1;
    if (trinaryArray[letter][trinaryIndex] > 0)
    {
      accumulator += curVal * trinaryArray[letter][trinaryIndex];
    }
    curVal *= 3;
  }
  word[letter] = (char)accumulator;
}

EDIT: This doesn't take into account MSB or LSB ordering. You may need to change the ordering of the inner loop to account for that ;).

Tawnos
  • 1,877
  • 1
  • 17
  • 26