获取无符号整数的最大值(按位不为零) [英] Obtaining max of unsigned integer with bitwise not on zero value

查看:263
本文介绍了获取无符号整数的最大值(按位不为零)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试获取某种无符号整数类型的最大值,而不包含任何像<limits>这样的标头.所以我想我只是将无符号整数值0的位翻转.

I'm trying to obtain the maximum value of a certain unsigned integer type without including any headers like <limits>. So I thought I'd simply flip the bits of the unsigned integer value 0.

#include <iostream>
#include <limits>

int main()
{
    std::cout << (~0U) << '\n'; // #1
    std::cout << (std::numeric_limits< unsigned >::max()) << '\n'; // #2
    return 0;
}

我对两者之间的细微差别不是很有经验.这就是为什么我问使用第一种方法是否可能发生某些意外行为或某些平台/体系结构问题.

I'm not very experienced on the subtle differences between these. Which is why I'm asking if some unexpected behavior or some platform/architecture issues could occur by using the first method.

推荐答案

...获取某种无符号整数类型的最大值,而不包含任何标头

... to obtain the maximum value of a certain unsigned integer type without including any headers

只需分配值-1

unsigned_type_of_choice max = -1;

-1(是int)转换为任何无符号类型,会导致 number的值比最大值减去-1大.

Conversion of the -1, which is an int, to any unsigned type results in the value of number that is one greater than the largest value minus 1.

以下内容不提供目标类型的最大值.当目标类型范围超出unsigned的范围(~0U的类型)时,它将失败. @Christopher Oicles

The following does not provide the maximum value of the destination type. It fails when the destination type range exceed the range of unsigned, which is the type of ~0U. @Christopher Oicles

// problem
unsigned_type_of_choice max_wannabe = ~0U;

这篇关于获取无符号整数的最大值(按位不为零)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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