views:

78

answers:

2

I have 4 numbers 0-3 which is an enum (objective-c) and I'd like to get the opposite using a formula. So if 0 is put into the formula it returns 2 and if it 2 is entered then it returns 0 (and same with 1 and 3).

The reason being (and it is programming related) that I want to get the opposite of an enum without having to do an if or switch statement. But this means that any formula (if it is possible must uncomplex, so that it is more efficient than using if or switch.

A: 
int newValue = 3 - originalValue;

Maybe cast to your enum type.

Edit: Sorry, this swaps 0 <=> 3 and 1 <=> 2, which I thought was meant with opposite.

For 0 <=> 2 and 1 <=> 3 you can use

int newValue = (originalValue + 2) % 4;
Eiko
im not sure how this works to do 0->2, 1->3, 2->0, 3->1?
Jonathan
That doesn't work. The result values should be `{2, 3, 0, 1}`.
Adrian
Sorry, misread "opposite" and extended it... But Guffa's xor is probably the better way to do this. More generally, you can use an array-lookup.
Eiko
thanks for your answer, it was interesting, but it seems Guffa's answer is better.
Jonathan
+7  A: 

The formula is very simple:

n = n ^ 2;

The bitvalues of 0 - 3 and how an exclusive or changes them:

n       ^10
---------------
0 = 00 : 10 = 2
1 = 01 : 11 = 3
2 = 10 : 00 = 0
3 = 11 : 01 = 1

Test (written in C#):

for (int n = 0; n <= 3; n++) {
  Console.WriteLine("{0} : {1}", n, n ^ 2);
}

Output:

0 : 2
1 : 3
2 : 0
3 : 1
Guffa
same comment as above, this wouldn't work.
Jonathan
@Jonathan: It works on my computer.
Adrian
it does work - perhaps you were thinking that ^ meant exponentiation? It is bitwise exclusive or. http://en.wikipedia.org/wiki/Bitwise_operation#XOR
Ken
sorry that comment was before it was changed. But now I do not understand the answer, so could you explain it a little more? (ken yes I did think that, thanks)
Jonathan
Is there a better explanation of it, than the wikipedia page?
Jonathan
@Jonathan: You simply do an exclusive or with the value 2 to get the conversion that you want. Check out the test code that I added above.
Guffa
@Jonathan: Exclusive or can be thought of as the bitwise equivalent of the `!=` operator. If the two corresponding bits are equal, the resulting bit is zero.
Guffa
And exactly these questions are the reason why you should not treat enums as ints. There was a good reason to use them in the first place: Readability and Maintainability. You'll lose both.
Eiko
Well this site:http://www.cprogramming.com/tutorial/bitwise_operators.html and the wiki page and I know understand it. Eiko, I'm only going to use it one place and it will be fairly obvious by the context of what it does.
Jonathan