夹紧增量整数? [英] Clamped Increment Integer?

查看:161
本文介绍了夹紧增量整数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否标准(或升压)为递增的整数确保它不随携带并启动回零,但保持在最大值的方法?或将我只需要创建自己的(这确实看起来应该包含一个小工具功能)。

 模板< typename的T>
无效增量(T&安培; X)
{
    如果(X =的std :: numeric_limits<!T> :: MAX())+ X;
}


解决方案

据我知道有没有这样的工具,所以你需要建立你自己的。

有是覆盖饱和算法的好文章: Branchfree饱和算法以及它们覆盖所有算术操作。其实例是在C,但不应该是很难翻译

有关你的情况,我们会在看加法。他们假设如下:

 的#include<&limits.h中GT;的typedef无符号u32b;的typedef签署S32B;

和无符号此外,他们提供以下code:

  u32b sat_addu32b(u32b X,u32b Y)
{
    u32b解析度= X + Y;
    RES | = - (RES< X);    返回水库;
}

和符号相加:

  S32B sat_adds32b(S32B X,S32B Y)
{
    u32b UX = X;
    u32b UY = Y;
    u32b解析度= UX +乌伊;    / *计算溢出的结果。 (不要更改UX的符号位)* /
    UX =(UX>> 31)+ INT_MAX;    / *强制编译器使用cmovns指令* /
    如果((S32B)((^ UX UY)|〜(乌伊^ RES))> = 0)
    {
        RES = UX;
    }    返回水库;
}

由于帕斯卡Cuoq在评论中指出的未签名的情况下,假定二进制补码应为绝大多数情况下是罚款,但标准不会使底层重新presentation假设。

Does the standard (or boost) provide a method for incrementing an integer ensuring that it doesn't carry over and start back at zero but keeps the value at max? Or would I simply have to create my own (this really does seem like a little utility function that should be included).

template<typename T>
void Increment(T& x)
{
    if(x != std::numeric_limits<T>::max()) ++x;
}

解决方案

As far as I know there is no such utility, so you would need to build you own.

There is a good article that covers saturating arithmetic: Branchfree Saturating Arithmetic and they cover all the arithmetic operations. Their examples are in C but should not be difficult to translate.

For your case we would be looking at addition. They assume the following:

#include <limits.h>

typedef unsigned u32b;

typedef signed s32b;

and for unsigned addition they provide the following code:

u32b sat_addu32b(u32b x, u32b y)
{
    u32b res = x + y;
    res |= -(res < x);

    return res;
}

and for signed addition:

s32b sat_adds32b(s32b x, s32b y)
{
    u32b ux = x;
    u32b uy = y;
    u32b res = ux + uy;

    /* Calculate overflowed result. (Don't change the sign bit of ux) */
    ux = (ux >> 31) + INT_MAX;

    /* Force compiler to use cmovns instruction */
    if ((s32b) ((ux ^ uy) | ~(uy ^ res)) >= 0)
    {
        res = ux;
    }

    return res;
}

As Pascal Cuoq notes in a comment the unsigned case assumes twos complement which should be fine for the vast majority of the cases but the standard does not make assumptions on the underlying representation.

这篇关于夹紧增量整数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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