有没有办法将一个整数值限制在一定范围内没有分支? [英] Is there a way to limit an integer value to a certain range without branching?

查看:192
本文介绍了有没有办法将一个整数值限制在一定范围内没有分支?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

只是出于好奇心。如果我有类似的:

Just out of curiosity. If I have something like:

if(x < 0)
    x = 0;
if(x > some_maximum)
    x = some_maximum;

return x;

有没有办法不分支?这是c ++。

Is there a way to not branch? This is c++.

补充:我的意思是在程序集中没有分支指令。这是一个MIPS架构。

Addendum: I mean no branch instructions in the assembly. It's a MIPS architecture.

推荐答案

有位技巧来找到两个数字的最小值或最大值,找到 min(max(x,0),some_maximum)。从此处

There are bit-tricks to find the minimum or maximum of two numbers, so you could use those to find min(max(x, 0), some_maximum). From here:

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

正常的方式,尽管分支

这篇关于有没有办法将一个整数值限制在一定范围内没有分支?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆