开发者

C converting an int to a bitshift operator

开发者 https://www.devze.com 2023-04-01 10:52 出处:网络
I can only use these symbols: ! ~ & ^ | + << >> Here is the table I need to achieve: input | output开发者_JS百科

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号