Возвратите нуль для отрицательных целых чисел

Не мой дизайн, но я использовал его несколько раз, введенный оператор переключения: http://community.bartdesmet.net/blogs/bart/archive/2008/03/30/a-functional-c-type-switch.aspx

Сохраненный меня так многие, если... еще, если... еще, если... еще, ЕСЛИ! операторы

8
задан Kirill V. Lyadvinsky 5 November 2009 в 19:48
поделиться

5 ответов

What's wrong with Math.Max?

You can do the equivalent without a branch using bitwise operations:

r = x ^ ((x ^ y) & -(x < y)); // == max(x, y)

If you substitute zero, it collapses to:

r = (y & -(0 < y)); // == max(0, y)

(Source: this list of bitwise tricks.)

If branches were extremely expensive on your platform, that might be worthwhile in some inner loop, I suppose, but it's pretty obscure and not the kind of thing I'd like to come across outside of an extremely time-sensitive function.

28
ответ дан 5 December 2019 в 04:42
поделиться

How about:

int i = ...;

return i & ~(i >> 31);

5
ответ дан 5 December 2019 в 04:42
поделиться

Приведенный ниже трюк поможет, и код читается так хорошо, что практически не требует комментариев;)

((((0x80000000 & i) >> 31)^1) * 0xFFFFFFFF) & i

затем снова

int temp = (0x80000000 & i); //get the most significant bit (1 for negative 0 for positive)
temp = (temp>>31)^1; //more it to the least significant and not it (we now have 0 for negative numbers and one for positive)

temp *= 0xFFFFFFFF; //get a lof of F's if it's positive or a lot of zeros if the number was negative

temp = temp & i; //and the F's/zeros with the original number

и вуаля ноль для всех отрицательных чисел и всех положительных оставлены без изменений

4
ответ дан 5 December 2019 в 04:42
поделиться

Not bitwise but different:

return (i + Math.abs(i))/2

EDIT:

return (int)(i/2f + Math.abs(i)/2f)
3
ответ дан 5 December 2019 в 04:42
поделиться

Short answer: No.

Bit operators do something very different, or rather are used for different problems.

If you know the size of your integers, you could test the highest (most significant) bit; if it's 1, the number is negative and you can act on that. But that would be a heck of a lot more work than the simple "<" test.

3
ответ дан 5 December 2019 в 04:42
поделиться
Другие вопросы по тегам:

Похожие вопросы: