Reputation: 311
Following an exercise and I am trying to obtain in an integer, whether a bit is 0 or 1 in a certain position.
Here is my code so far:
Console.WriteLine("input number");
int number = int.Parse(Console.ReadLine());
Console.WriteLine("input position");
int position = int.Parse(Console.ReadLine());
int place = 1;
int bit = place << position;
Console.WriteLine(bit);
So the user inputs a number (the integer, lets say 10) then a bit position (lets say 5) and the program should tell me if or not the 5th bit (from the right) is a 0 or one.
However instead its telling me the value that bit represents (1, 2, 4, 8, 16, 32, 64 etc.)
I really am uncertain what i've missed, I went ahead and looked up the solution (which I realised did not need user input) and that gave me the same error.
int n = 35;
int p = 6;
int i = 1;
int mask = i << p;
The question, quote, says "Value of the bit on the position p in the number (0 or 1)." so it wants 0 or 1 as output. So I'm stumped, really need some help please. I may be overthinking things and missing something obvious but I've failed to find a solution.
Upvotes: 1
Views: 123
Reputation: 317
you do a bit shift: http://msdn.microsoft.com/fr-fr/library/a1sway8w.aspx
i think you should test your bit with the following code:
if(valueToTest & 32 == 32) => Bit is active
Upvotes: 0
Reputation: 101681
You need bitwise AND
&
operator
int place = 1;
int bit = place << position;
if((number & bit) == bit) Console.WriteLine("{0}. bit is 1",position);
else Console.WriteLine("{0}. bit is 0", position);
Upvotes: 1
Reputation: 56536
int n = 35;
int p = 6;
int i = 1;
int mask = i << p;
At this point, you have the mask == 64
, and n == 35
. Now you need to check or apply the mask in some way. A good way to do this is with the &
operator, which is a bitwise AND. In the case of a mask with one bit set to 1
(like your mask
), this will tell you whether n
has that bit set to 1
or 0
.
int masked = n & mask;
// masked will be 0 or 64; since we want 0 or 1...
int result = masked != 0 ? 1 : 0;
// although I'd go with a bool if possible, because it makes more sense
bool boolResult = masked != 0;
Upvotes: 1