Reputation: 39
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;
}
Upvotes: 0
Views: 84
Reputation: 46037
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;
Upvotes: 1