Converting integers to binary

this is my code in C++

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
#include <iostream>

using namespace std;


int Bit(long x, unsigned int n)
{
	int constant = 1 << (n-1);

	if( x & constant )
	{
	return 1;
 }
 return 0;
}

int main()
{
long integer;
cout << "Type a Number: ";
cin >> integer;

unsigned int sigBit;
cout << "Enter Bit Number:";
cin >> sigBit;

int Bitwise = Bit(integer,sigBit);

cout << "The " << sigBit <<" bit value is:" << Bitwise << "\n";
cout << "The binary representation of the whole decimal: ";

int binary;
for(int i = 0; i < 32; i++)
{
binary = Bit(integer,i);
cout << binary;
}



cout << "\n";
return 0;
}


for some reason the output is the opposite of what I wanted.
I cant seem to find the error, I was hoping someone could help me on this.
thank you
Last edited on
Yep, you are shifting 1 over a certain number of bits and then outputing it. Then you return 1, never anything else.

I think this would work better for you:

1. Shift x over by n-1 bits,
2. Mask the 1's bit
3. return the result

1
2
3
4
int Bit(long x, unsigned int n)
{
  return (0x00000001 & (x >> (n-1)));
}


Oh wait, your function does work! My bad.

Your problem is just in the for loop. Remember the console is expecting us to print the most significant bit first (the 32nd bit) not the least significant bit (the 1st bit).

Just start at 32 and work your way backwards:
1
2
3
4
5
for(int i = 32; i > 0; i--)
{
	int binary = Bit(integer,i);
	cout << binary;
}
ah i see,
thanks for the help.
learnt something new today!
Topic archived. No new replies allowed.