-
Bitwise operators help ~
First please view my code below.
Code:
#include <stdio.h>
#include <conio.h>
void ReduceOddNumber(int n, int *result);
int main(void)
{
int n, result;
printf("Input integer: ");
scanf("%d", &n);
if( n & 1 == 1) // if last bit in numbers is 1, 'n' is odd , 0 for even
{
printf("Odd number.\n");
ReduceOddNumber(n, &result);
}
else
{
printf("Even number.\n");
}
}
void ReduceOddNumber(int n, int *result)
{
result =
}
I was newly learn Bitwise operators and now I have no ideas how to start with a simple thing. How can I reduce number by 1 by Bitwise operators? E.g. User input 15 then my program change to 14? Very thanks you.
-
You want to clear the bit that causes n&1 to give a non-zero result, but leave all the other bits of n untouched.
-
Did you mind show me how to done that? Because I really have no idea how...I am totally new at this chapter.
-
If I gave you the clearest answer it would be like solving the problem.
You need to know what the operators do to get anywhere.
-
Ok...I try change into the following code
Code:
void ReduceOddNumber(int n, int *result)
{
*result = n << 1 ;
}
When I input 5 it become 10 I wonder why?
-
Now I get it ~ If I change into *result = n ^ 1 ; It works....But I still don't know how those operators works. So I need some explanation...
-
I recommend reading the FAQ on this topic, it should explain all the operators to you. Once you understand what they do, you just have to glue them together to do what you want. What you discovered happens to be one of the simplest answers because it involves the fewest operations. Basically because 1 XOR 1 == 0, you get what you want because all odd numbers on your system will have the one bit set. There are better ways to do what you want, but I'll leave it to you to discover if you care (it's not that hard!)
-