The code is as follows:
Copy Code code as follows:
#include <iostream> //Convert decimal number to binary number, bitwise operation
using namespace std;
int Main ()
{
unsigned short i;
cout << "Please enter a positive integer less than 65536" << 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, by the way review the wonders of the bit operation.
This is a program that converts an unsigned decimal number to a standard 16-bit binary number.
The main part of the program, the for statement from 15 to 0, a total of 16 times the binary number of each of the judgments of the operation. The condition judgment inside the loop body is applied to the & operation (and operation) and the << operation (left shift operation) in the bit operation. << operation means that the 1 binary form as a whole to the left J-position, left after the low fill 0, moved out of the high portion was discarded. For example, when J is 15 o'clock, the value of an expression (1<<j) is 1000000000000000; When J is 10 o'clock, the value is 0000010000000000.
So the value of i& (1<<J) is the equivalent of removing the J bit of the I binary (the J bit of I and (1<<j) as the J bit (by the above can be 1) and only if the J bit of I is 1 the time value is true). The binary form of I after the loop.
Some children's shoes may feel the use of mod (take the remainder) operation can achieve the effect, however, the "personality" of the bitwise operation determines that it directly to the data binary form of the operation of the fast (the general computer data storage Basic form of binary form), two of the same algorithm, the use of the bit operation will improve the speed of the program.
The above mentioned is the entire content of this article, I hope you can enjoy.