hey..I need to convert a 8 value bool array to char.How can I do this?

You can use the bool array as a "bit-position" array for the representation of a char.

#include <iostream>

using std::cout;
using std::cin;
using std::endl;

int main(){
     bool bits[] = {0, 1, 0, 0, 0, 0, 0, 1};
     char c = 0;
     for(int i = 0; i < 8; i++)
           c += (bits[i] >> i); // 0 or 1 times 2 to the ith power
     cout << c << endl; // should print out A
     cin.get();
     return 0;
}

Edit: I'm not near a compiler, so the bit-shifting operator may need to be switched but the logic is straightfoward.

Hopefully this helps! =)

-Alex

I had

char boolsToChar(bool* bools){
     char c = 0;
     for( int i = 0; i < 8; i++ )
          if( bools[i] ) 
              c += pow(2,i);
     return c;
}

but clearly this is not as nice a solution as above, For multiple reasons.

One being that I get a warning for converting a double to a char and two I have a conditional statment that i clearly don't require

Anyhow the solution above compiled for me, but I needed to change it around a little to come up with 'A'.

bool bits[] = {1, 0, 0, 0, 0, 0, 1, 0};
    char c = 0;
    for(int i = 0; i < 8; i++)
           c += (bits[i] << i); // 0 or 1 times 2 to the ith power
    cout << c << endl; // should print out A
    cin.get();

Hmm, try changing char to unsigned (if it exists @_@ )

-Alex

Edit: I am really tired #_#

I didn't realize I made the array back-asswards XD

XP

How about this, rather unusual method ;)

#include <iostream>

struct octet {
  union {
    char val;
    struct {
      unsigned h : 1;
      unsigned g : 1;
      unsigned f : 1;
      unsigned e : 1;
      unsigned d : 1;
      unsigned c : 1;
      unsigned b : 1;
      unsigned a : 1;
    };
  };
};

int main() {
  bool bits[] = {0, 1, 1, 0, 0, 0, 0, 1};

  octet o;
  o.a = bits[0];
  o.b = bits[1];
  o.c = bits[2];
  o.d = bits[3];
  o.e = bits[4];
  o.f = bits[5];
  o.g = bits[6];
  o.h = bits[7];

  std::cout << o.val; // 01100001 = 'a'
  std::cin.ignore();
}

Theres practically no maths involved :)

Thanks a lot! :D

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.