Bit operation to achieve decimal conversion to binary

  • 2020-04-02 03:01:36
  • OfStack

The code is as follows:


 #include <iostream>        //Convert decimal number to binary number, bit operation
 using namespace std;
 int main()
 {
        unsigned short i;
        cout << " Please enter a less than 65536 The positive integer " << endl;
        cin >> i;
        for(int j=15; j >= 0; j--)
        {
               if ( i & ( 1 << j) ) cout << "1";
               else cout << "0";
        }
        cout << endl;
     return 0;
 }

Analysis:

      Analyze the algorithm principle of this program, and review the magic of bit operation.
    This is a program that converts unsigned decimal Numbers into standard 16-bit binary Numbers.
      In the body of the program, the for statement decrements from 15 to 0 16 times for each bit of the binary number. The conditional judgment inside the loop body USES the ampersand (and) sum of bit operations < < Operation (left shift operation). < < Operation means that the whole binary form of 1 is shifted to the left by j bit, and the lower part is supplemented by 0 after moving to the left, and the higher part moved out is discarded. For example, when j is 15, the expression (1) < < The value of j) is 1000000000000000; When j is 10, the value is 0000010000000000.
      So I & (1) < < The value of j) is equivalent to taking the JTH bit out of the binary of I < < The JTH bit of j) (from the above can be, is 1) and operation, the value is true only if the JTH bit of I is 1). I get the binary form of I after the loop.
      Some children may feel with the mod (take over) operation still can achieve the effect, but the "personality" determines the bit operations it directly to the promptness of operating data of binary form (general basic form of computer data storage for binary form), two of the same algorithm procedures, using an improved after operation can make the program speed.

The above is all the content of this article, I hope you can enjoy it.


Related articles: