Decimal to Binary

What is your question?

Avoid the use of <bits/stdc++.h>. It is not a standard headers. Use the standard headers instead.

PLEASE ALWAYS USE CODE TAGS (the <> formatting button) when posting code.
It makes it easier to read your code and also easier to respond to your post.
http://www.cplusplus.com/articles/jEywvCM9/
Hint: You can edit your post, highlight your code and press the <> formatting button.
What about:
1
2
3
4
5
6
7
8
9
10
void decimalToBinary(int n)
{
    static const int MSB_MASK = 0x1 << ((sizeof(int) * 8U) - 1U);
    for (size_t i = 0; i < sizeof(int) * 8U; ++i)
    {
        std::cout << ((n & MSB_MASK) ? '1' : '0');
        n <<= 1;
    }
    std::cout << std::endl;
}


...or, without "leading" zeros:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
void decimalToBinary2(int n)
{
    static const int MSB_MASK = 0x1 << ((sizeof(int) * 8U) - 1U);
    size_t i = 0;
    for (; !(n & MSB_MASK); ++i)
    {
        n <<= 1;
    }
    for (; i < sizeof(int) * 8U; ++i)
    {
        std::cout << ((n & MSB_MASK) ? '1' : '0');
        n <<= 1;
    }
    std::cout << std::endl;
}
Last edited on
Topic archived. No new replies allowed.