Link to home
Start Free TrialLog in
Avatar of pcomb
pcombFlag for United States of America

asked on

C++ Bitwise

I have an array of Char and I am trying to output the bits. I am a little confused on the concepts of mask and shift (looking for a good article to understand these?)

Not sure if either option 1 or option 2 are correct

  for (int x = 0; i < a.arraySize; x++)
   {
         int test1 = sizeof( char );
   const int SHIFT = 8 * sizeof( char ) - 1;
   const unsigned MASK = 1 << SHIFT;

   os << setw( 10 ) <<  " start =  " << a.barray[x] << " = ";
   char test = a.barray[x];
    unsigned test2 = a.barray[x];
         // display bits
         for ( unsigned j = 1; j <= SHIFT + 1; j++ )
         {
               // Option 1
              //  os << ( a.barray[j] & MASK ? '1' : '0' );
            //  a.barray[j] <<= 1; // shift value left by 1
                Option 2
              os << ( test2 & MASK ? '1' : '0' );
              test2 <<= 1; // shift value left by 1
              if ( j % 8 == 0 ) // output a space after 8 bits
                   os << ' ';
         } // end for
   } // end for
Avatar of Kent Olsen
Kent Olsen
Flag of United States of America image

Hi pcomb,

You seem to have the right idea.  :)  A small suggestion though is to leave the data "as is" and shift the mask.

Assume that the char variable contains an 'A'.  The numeric value of the 'A' is 65 decimal, 41 hex, 101 octal, and 100001 binary.  The looping that you're writing should display the binary value, showing the bits from left to right.

The inner loop should probably have look similar to this:

unsigned char Value = 'A';
unsigned char Mask;

for  (Mask = 0x80; Mask; Mask >>= 1)
  os << (Value & Mask) ? '1' : '0';

Open in new window


You can wrap this tight loop with the controls to process the entire array, too.


Good Luck,
Kent
ASKER CERTIFIED SOLUTION
Avatar of HooKooDooKu
HooKooDooKu

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial