I have a code like this that converts a short integer to binary, but zeros are printed at the beginning. So here's how to make sure that these zeros are not displayed, and the output starts from the first one? At the same time, using standard language operators and bitwise operations.
int main()
{
unsigned short int k;
while (true)
{
cin >> k;
if (!k)
{
break;
}
for (int i = 0; i < 16; i++)
{
cout << (k >> 15);
k <<= 1;
}
cout << endl;
}
With recursion, you might do:
void print_binary(unsigned int n)
{
if (n >> 1 != 0) print_binary(n >> 1);
std::cout << (n & 1);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.