簡體   English   中英

如何與numeric_limits進行比較 <int64_t> ::分鍾()

[英]How to compare to numeric_limits<int64_t>::min()

考慮到符號( +1-1 )是已知的,並且有一個代碼可以解析無符號整數。 無符號整數可以等於-numeric_limits<int64_t>::max() 如何正確比較而不觸發未定義的行為?

int8_t sign = /* +1 or -1 */;
uint64_t result = /* parse the remaining string as unsigned integer */;
if( result > uint64_t(numeric_limits<int64_t>::max()))
{
    if(sign == 1) return false; // error: out of range for int64_t
    // Is the below code correct or how to implement correctly its intent?
    if(result == uint64_t(-numeric_limits<int64_t>::min()))
    {
        return true;
    }
    return false;
}

正如Holt所說,你實際上是在假設2的補碼算法。 因此,您可以用max+1替換-min

if(result == uint64_t(numeric_limits<int64_t>::max()) + 1)

這可以避免在否定最小值時產生的未定義行為(有符號整數溢出)。

驗證您的系統是否真正使用2的補碼(取決於您希望遵守C ++標准的嚴格程度)可能是個好主意。 這可以通過比較-maxmin來實現:

if (numeric_limits<int64_t>::max() + numeric_limits<int64_t>::min() == 0)
{
    // If not two's complement:
    // Too large absolute value == error, regardless of sign
    return false;

    // on all sane (2's complement) systems this will be optimized out
}

minmax之間沒有其他關系; 在這里解釋。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM