Bitwise Operators - C++ Operator

C++ examples for Operator:Bit Operator

Introduction

Operator NameDescription
& bitwise ANDset to 1 if the corresponding bits in the two operands are both 1.
| bitwise inclusive OR set to 1 if one or both of the corresponding bits in the two operands is 1.
^ bitwise exclusive OR set to 1 if exactly one of the corresponding bits in the two operands is 1.
<< left shift Shifts bits of the first operand left by the number of bits specified by the second operand; fill from right with 0 bits.
>> right shift with sign extension Shifts bits of the first operand right by the number of bits specified by the second operand; the method of filling from the left is machine dependent.
~ bitwise complement All 0 bits are set to 1 and all 1 bits are set to 0.

Printing an unsigned integer in bits.

Demo Code


 #include <iostream> 
 #include <iomanip> 
 using namespace std; 

 void displayBits( unsigned ); // prototype 

int main() /*w ww.j a va  2  s .com*/
{ 
    unsigned inputValue; // integral value to print in binary 

    cout << "Enter an unsigned integer: "; 
    cin >> inputValue; 
    displayBits( inputValue ); 
}

// display bits of an unsigned integer value 
void displayBits( unsigned value ) 
{ 
    const int SHIFT = 8 * sizeof( unsigned ) - 1; 
    const unsigned MASK = 1 << SHIFT; 

    cout << setw( 10 ) << value << " = "; 

    // display bits 
    for ( unsigned i = 1; i <= SHIFT + 1; ++i ) 
    { 
       cout << ( value & MASK ? '1' : '0' ); 
       value <<= 1; // shift value left by 1 

       if ( i % 8 == 0 ) // output a space after 8 bits 
           cout << ' '; 
    }

    cout << endl; 
}

Result


Related Tutorials