简体   繁体   中英

opposite of enum (using formula) (objective-c)

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.

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
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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM