• 10
• 12
• 12
• 14
• 16

# 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.

## 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));
}


##### Share on other sites
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 on other sites
try:
1 << (2*button - 2)

##### Share on other sites
Quote:
 Original post by Samurai JackGreetings!I'm searching for a quick way to solve this function:f(x) = 1 << (x*2)Which would give me numbers:f(1) = 1 |*4f(2) = 4 |*4f(3) = 16 |*4f(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 on other sites
As Smitty pointed out, we or he doesn't know which function is to be solved [lol]

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

##### 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.