C converting an int to a bitshift operator
I can only use these symbols:
! ~ & ^ | + << >>
Here is the table I need to achieve:
input | output开发者_JS百科
--------------
0 | 0
1 | 8
2 | 16
3 | 24
With the output I am going to left shift a 32 bit int over.
Ex.
int main()
{
int myInt = 0xFFFFFFFF;
myInt = (x << (myFunction(2)));
//OUTPUT = 0xFFFF0000
}
int myFunction(int input)
{
// Do some magic conversions here
}
any ideas????
Well, if you want a function with f(0) = 0
, f(1) = 8
, f(3) = 24
and so on then you'll have to implement f(x) = x * 8
. Since 8 is a perfect power of two the multiplication can be replaced by shifting. Thus:
int myFunction(int input)
{
return input << 3;
}
That's all.
精彩评论