DaniWeb IT Discussion Community

DaniWeb IT Discussion Community (http://www.daniweb.com/forums/index.php)
-   C++ (http://www.daniweb.com/forums/forum8.html)
-   -   converting bool[8] to char (http://www.daniweb.com/forums/thread158909.html)

AutoC Nov 22nd, 2008 6:04 am
converting bool[8] to char
 
hey..I need to convert a 8 value bool array to char.How can I do this?

Alex Edwards Nov 22nd, 2008 6:35 am
Re: converting bool[8] to char
 
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

Paul.Esson Nov 22nd, 2008 7:13 am
Re: converting bool[8] to char
 
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();

Alex Edwards Nov 22nd, 2008 7:18 am
Re: converting bool[8] to char
 
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

William Hemsworth Nov 22nd, 2008 7:56 am
Re: converting bool[8] to char
 
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 :)

AutoC Nov 22nd, 2008 8:21 am
Re: converting bool[8] to char
 
Thanks a lot! :D


All times are GMT -4. The time now is 6:07 am.

Forum system based on vBulletin Copyright ©2000 - 2009, Jelsoft Enterprises Ltd.
©2003 - 2009 DaniWeb® LLC