I have a task to practice and I just can't get the solution. It should be noted that I am a total beginner. There is 1min for the exercise, so it should be child's play. But I am racking my brains over it.
I am supposed to write an expression for the following :
Let x and k be variables of type int. Formulate a C condition with bitwise operator that is true exactly when x is less than 2^(k-1).
I would have done this with the ?-operator. So something like
( ) ? 1 : 0
But which condition must be in the brackets? I can't think of a bitwise operator that can be used to compare less than?
I really don't have any Idea :/
CodePudding user response:
It seems you mean something like the following
if ( x < 1 << k - 1 ) { /*...*/ }
provided that the expression k - 1
is not negative and the expression 1 << k - 1
is representable as a positive value in an object of the type int
.
CodePudding user response:
Let x and k be variables of type int.
int x;
int k;
Formulate a C condition with bitwise operator that is true exactly when x is less than 2^(k-1).
Start with directly translating it:
if ( x < pow(2,k-1) ) { ... }
Then remove the call to pow
using bitwise operators
2-to-the-power-of k-1 is: 1<<(k-1)
Examples: to help clarify
2 ^ 3 == 1 << 3 == 8
2 ^ 5 == 1 << 5 == 32
So the final expression is:
( x < 1<<(k-1) ); // Result will either be 1 or 0
There is no need to use ternary ?:
operator.
The boolean expression <
will evaluate to 1 or 0 by itself!