0

The following code gives the wrong binary output: The input is a HEX number and the output should be a binary number.

It always outputs:

0    
0    
0    
0

How can I change it so it outputs the right binary number?

#include <iostream>

using namespace std;

int main ()
{   

int Number;
cin >> Number;
bool Binary[sizeof(int) * CHAR_BIT];

for(unsigned int i = 0; i < sizeof(int) * CHAR_BIT; i++)
    Binary[(sizeof(int) * CHAR_BIT - 1) - i] = Number & (1 << i);

for(unsigned int i = 0; i < sizeof(int); i++)
    std::cout << Binary[i] << std::endl;

system ("pause");

return 0;

}
3
  • 1
    What does this have to do with your question title? Commented Mar 7, 2012 at 9:42
  • @Joriek, edit the title so that it reflects your problem. Commented Mar 7, 2012 at 9:52
  • 1
    "wrong output" does not reflect the problem to a sufficiently descriptive degree. It should aid somebody to find this post in a web search in the future. Commented Mar 7, 2012 at 10:17

1 Answer 1

1

You are calculating it right but printing only sizeof(int) bits, not all bits. In last print loop use i < sizeof(int) * CHAR_BIT.

for(unsigned int i = 0; i < sizeof(int) * CHAR_BIT; i++)
    std::cout << Binary[i] << std::endl;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.