简体   繁体   English

可以包含给定有符号积分的正值的最小无符号int?

[英]smallest unsigned int that can contain the positive values of a given signed integral?

Can the smallest unsigned int that can contain the positive values of a given signed integral type be determined at compile time? 可以在编译时确定可以包含给定有符号整数类型的正值的最小无符号int吗?

So the smallest unsigned integral type that is large enough to hold the max value of a given signed integral type. 因此,最小的无符号整数类型要足够大以容纳给定有符号整数类型的最大值。

A good starting point is that 2 is the base-number and we need to take into account the 2-based logarithm. 一个好的起点是2是基数,我们需要考虑基于2的对数。 General rules: 通用规则:

  1. If an unsigned integer has a sizeof n bytes, then the largest positive number is (2^(8 * n)) - 1 如果无符号整数的sizeof n个字节,则最大正数为(2 ^(8 * n))-1

  2. If a signed integer has a sizeof n bytes, then the largest positive number is (2^(8 * n - 1)) - 1 如果有符号整数的sizeof n个字节,则最大正数为(2 ^(8 * n-1))-1

As a result, you need to determine the sizeof a variable of the given type and see if it has a sign. 结果,您需要确定给定类型的变量的sizeof ,并查看它是否带有符号。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM