• Advertisement
Sign in to follow this  

function(1, 2, 3, 4) - y=1,4,16,64,256

This topic is 3939 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Greetings! I'm searching for a quick way to solve this function: f(x) = 1 << (x*2) Which would give me numbers:
f(1) = 1   |*4
f(2) = 4   |*4
f(3) = 16  |*4
f(4) = 64  |*4=
f(5) = 256 
It has to be done without a for senence. Is it possible to use only 1 shift operator? Like: f(x) = a << x; or something like that? Of course, i cold do as following: f(x) = 1 << (x << 1) but it looks far to ugly. The code:
inline BOOL IsMouseButtonDown(int button)
{
    return mousebuttons & (1 << (button << 1));
}
I would like just one shift if possible. One method is also POW (powers):
inline BOOL IsMouseButtonDown(int button)
{
    return mousebuttons & (power(4,button));
}
Thank you in advance!

Share this post


Link to post
Share on other sites
Advertisement
Given that only a handful of values will even fit in a 32 bit number, if it needs to be fast I'd suggest just using a lookup table. But it doesn't need to be fast. What, exactly, is wrong with 1 << (x*2)?

Share this post


Link to post
Share on other sites
Quote:
Original post by Samurai Jack
Greetings!

I'm searching for a quick way to solve this function:

f(x) = 1 << (x*2)

Which would give me numbers:

f(1) = 1 |*4
f(2) = 4 |*4
f(3) = 16 |*4
f(4) = 64 |*4=
f(5) = 256


That isn't what it would give you... It would give you:

f(1) = 1
f(2) = 16
f(3) = 64
f(4) = 256
f(5) = 1024

EDIT: I think I misunderstood your post.

Share this post


Link to post
Share on other sites
I completely agree with Sneftel. What's with the irrational fear of statements containing 3 or more operators?

Share this post


Link to post
Share on other sites
Quote:
I would like just one shift if possible. One method is also POW (powers):


Shift is one of the elementary operations, it's present on just about every chipset, and is fastest possible approach to bit manipulations. In many cases, (1<<x) will outperform lookup in a table.

Power function on the other hand is one of the most expensive operations. While for some value it gives identical results, it's the method *not* to use for bit manipulations.

inline BOOL IsMouseButtonDown(int button) {
return mousebuttons & (1 << (button << 1));
}
This is as good as it gets.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement