gpt4 book ai didi

ios - 有没有更好的方法来确定两个枚举值之间的距离?

转载 作者:太空宇宙 更新时间:2023-11-04 06:28:14 25 4
gpt4 key购买 nike

我有一个具有 8 位移位值的枚举。我希望能够确定任意两个值相距多远。如果值只是增加整数,这将很简单。这是我现在得到的。

typedef NS_ENUM(NSInteger, TestEnum) {
TestEnumValue1 = 1 << 0,
...
TestEnumValue8 = 1 << 7
};

TestEnum left = TestEnumValue8;
TestEnum right = TestEnumValue3;

TestEnum high = MAX(left, right);
TestEnum low = MIN(left, right);

int distance = 0;
int maximumEnum = 8;
int cumulativeResult = high;
for (int i = 0; i < maximumEnum; i++)
{
cumulativeResult = cumulativeResult / 2;
if (cumulativeResult == low)
{
distance = i;
break;
}
}
NSLog (@"Distance is %d", distance);

上面的方法看起来效果不错,但这是最好的方法吗?

最佳答案

忽略使用枚举是否合适,试试这个:

TestEnum left = TestEnumValue8;
TestEnum right = TestEnumValue3;

TestEnum high = MAX(left, right);
TestEnum low = MIN(left, right);

int distance = 0;
while (low < high) {
low <<= 1;
distance++;
}

NSLog (@"Distance is %d", distance);

请记住,这仅在 leftright 都设置了一个“标志”时才有效。

关于ios - 有没有更好的方法来确定两个枚举值之间的距离?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23483628/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com