Mega Code Archive

 
Categories / C++ Tutorial / Data Types
 

Printing an unsigned integer in bits

#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