这是一个非常简单的问题(我认为),是否有提供变量类型 (例如整数)限制的 STL 库方法 ?我知道这些限制在不同的计算机上有所不同,但必须有办法通过某种方法来获得它们,对吧?
另外,写一个计算变量类型限制的方法真的很难吗?
我只是好奇!:)
谢谢 ;)。
// numeric_limits example
// from the page I linked
#include <iostream>
#include <limits>
using namespace std;
int main () {
cout << boolalpha;
cout << "Minimum value for int: " << numeric_limits<int>::min() << endl;
cout << "Maximum value for int: " << numeric_limits<int>::max() << endl;
cout << "int is signed: " << numeric_limits<int>::is_signed << endl;
cout << "Non-sign bits in int: " << numeric_limits<int>::digits << endl;
cout << "int has infinity: " << numeric_limits<int>::has_infinity << endl;
return 0;
}
我看到已经给出了“正确”的答案:使用<limits>
并让魔法发生。我碰巧发现这个答案不令人满意,因为问题是:
写一个计算变量类型限制的方法真的很难吗?
答案是:整数类型容易,浮点类型难。执行此操作需要 3 种基本类型的算法。有符号、无符号和浮点。每个都有不同的算法来获取最小值和最大值,实际代码涉及一些位旋转,在浮点的情况下,除非你有一个与浮点大小相同的已知整数类型,否则你必须循环类型。
所以,就在这里。
未签名很容易。最小值是所有位为 0 时,最大值是所有位为 1 时。
const unsigned type unsigned_type_min = (unsigned type)0;
const unsigned type unsigned_type_max = ~(unsigned type)0;
对于有符号,最小值是设置了符号位但所有其他位都为零时,最大值是设置了除符号位之外的所有位。在不知道类型大小的情况下,我们不知道符号位在哪里,但我们可以使用一些位技巧来使其工作。
const signed type signed_type_max = (signed type)(unsigned_type_max >> 1);
const signed type signed_type_min = (signed type)(~(signed_type_max));
对于浮点数,有 4 个限制,虽然只知道正限制就足够了,但负限制只是符号反转的正限制。表示浮点数的方法可能有很多种,但对于那些使用二进制(而不是基数 10)浮点数的方法,几乎每个人都使用 IEEE 表示。
对于 IEEE 浮点数,最小正浮点值是当指数的低位为 1 且所有其他位为 0 时。最大的负浮点值是它的按位倒数。但是,如果没有已知与给定浮点类型大小相同的整数类型,除了执行循环之外,没有其他方法可以执行此位操作。如果您有一个整数类型,并且您知道它与浮点类型的大小相同,则可以将其作为单个操作执行。
const float_type get_float_type_smallest() {
const float_type float_1 = (float_type)1.0;
const float_type float_2 = (float_type)0.5;
union {
byte ab[sizeof(float_type)];
float_type fl;
} u;
for (int ii = 0; ii < 0; ++ii)
u.ab[ii] = ((byte*)&float_1)[ii] ^ ((byte*)&float_2)[ii];
return u.fl;
}
const float_type get_float_type_largest() {
union {
byte ab[sizeof(float_type)];
float_type fl;
} u;
u.fl = get_float_type_smallest();
for (int ii = 0; ii < 0; ++ii)
u.ab[ii] = ~u.ab[ii];
return -u.fl; // Need to re-invert the sign bit.
}
(与C有关,但我认为这也适用于C++)
您也可以尝试“ inquire ”,这是一个可以为您的编译器重新创建 limits.h 的脚本。来自 projetc 主页的引述:
这是一个程序,它决定了 C 编译器和运行它的机器的许多属性,例如最小和最大 [un]signed char/int/long、float/[long] double 的许多属性等等。
作为一个选项,它生成 ANSI C float.h 和 limits.h 文件。
作为进一步的选择,它甚至会检查编译器是否正确读取了头文件。
对于编译器来说,这是一个很好的测试用例,因为它使用许多限制值来练习它们,例如最小和最大浮点数。
#include <limits>
std::numeric_limits<type>::max() // min() etc