简体   繁体   English

与枚举相反(使用公式)(目标-c)

[英]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. 我有4个数字0-3,这是一个枚举(objective-c),我想使用公式来得出相反的结论。 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). 因此,如果将0放入公式中,则返回2;如果输入2,则返回0(与1和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. 原因是(与编程相关)我想得到枚举的对立而不必执行if或switch语句。 But this means that any formula (if it is possible must uncomplex, so that it is more efficient than using if or switch. 但这意味着任何公式(如果可能)都必须不复杂,因此它比使用if或switch更有效。

The formula is very simple: 公式很简单:

n = n ^ 2;

The bitvalues of 0 - 3 and how an exclusive or changes them: 0-3的位值以及如何对其进行异或运算:

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

Test (written in C#): 测试(用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. 编辑:抱歉,这交换0 <=> 3和1 <=> 2,我认为这是相反的意思。

For 0 <=> 2 and 1 <=> 3 you can use 对于0 <=> 2和1 <=> 3,您可以使用

int newValue = (originalValue + 2) % 4;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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