C++ Tutorial/Operators statements/complement

Материал из C\C++ эксперт
Перейти к: навигация, поиск

Demonstrate bitwise complement

<source lang="cpp">#include <iostream> using std::cout;

  1. include <iomanip>

using std::endl; using std::setw; void displayBits( unsigned ); int main() {

  unsigned number1;
  unsigned number2;
  unsigned mask;
  unsigned setBits;
  number1 = 21845;
  cout << "\nThe one"s complement of\n";
  displayBits( number1 );
  cout << "is" << endl;
  displayBits( ~number1 );
  return 0;

} //Quote from //C++ How to Program (5th Edition) (How to Program) (Paperback) //by Harvey & Paul) Deitel & Associates //Publisher: Prentice Hall; 5 edition (January 5, 2005) //Language: English //ISBN-10: 0131857576 //ISBN-13: 978-0131857575 void displayBits( unsigned value ) {

  const int SHIFT = 8 * sizeof( unsigned ) - 1;
  const unsigned MASK = 1 << SHIFT;
  cout << setw( 10 ) << value << " = ";
  for ( unsigned i = 1; i <= SHIFT + 1; i++ ) {
     cout << ( value & MASK ? "1" : "0" );
     value <<= 1;
     if ( i  8 == 0 )
        cout << " ";
  }
  cout << endl;

}</source>

The one"s complement of
     21845 = 00000000 00000000 01010101 01010101
is
4294945450 = 11111111 11111111 10101010 10101010

The complement of the number

<source lang="cpp">#include <iostream> using namespace std; void show_binary(unsigned int u); int main() {

 unsigned u = 123;
 cout << "Here"s the number in binary: ";
 show_binary(u);
 cout << "Here"s the complement of the number: ";
 show_binary(~u);
 return 0;

} void show_binary(unsigned int u) {

 int t;
 for(t=128; t>0; t = t/2)
   if(u & t) cout << "1 ";
   else cout << "0 ";
 cout << "\n";

}</source>

Here"s the number in binary: 0 1 1 1 1 0 1 1
Here"s the complement of the number: 1 0 0 0 0 1 0 0