Printing an unsigned integer in bits : binary bit « Data Types « C++ Tutorial






#include <iostream>
using std::cout;
using std::cin;
using std::endl;

#include <iomanip>
using std::setw;

int main()
{
   unsigned value = 123;
   const int SHIFT = 8 * sizeof( unsigned ) - 1;
   const unsigned MASK = 1 << SHIFT;

   for ( int i = 1; i <= SHIFT + 1; i++ ) 
   {
      cout << ( value & MASK ? '1' : '0' );
      value <<= 1;

      if ( i % 8 == 0 )
         cout << ' ';
   }

   cout << endl;
   return 0;
}
00000000 00000000 00000000 01111011








2.13.binary bit
2.13.1.Printing an unsigned integer in bits
2.13.2.Display the bits within a byte.
2.13.3.Bitwise operators: Complement, AND, OR
2.13.4.Bitwise operator: ^
2.13.5.Use masks to select or set a particular flag bit