C++变量类型限制

Jes*_*ond 12 c++ variables types limits

这是一个非常简单的问题(我认为),是否有一个STL库方法提供变量类型的限制 (例如整数) 我知道这些限制在不同的计算机上有所不同,但必须有办法让他们通过一种方法,对吗?

另外,编写一个计算变量类型限制的方法真的很难吗?

我只是好奇!:)

谢谢 ;).

GMa*_*ckG 38

用途std::numeric_limits:

// 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;
}
Run Code Online (Sandbox Code Playgroud)


Joh*_*ler 12

我看到已经给出了"正确"的答案:使用<limits>并让魔法发生.我碰巧发现答案不满意,因为问题是:

编写一个计算变量类型限制的方法真的很难吗?

答案是:对于整数类型很容易,对于float类型很难.您需要执行3种基本类型的算法.有符号,无符号和浮点.每种方法都有不同的算法来获得最小值和最大值,而实际代码涉及一些小问题,在浮点的情况下,除非你有一个与浮点大小相同的已知整数类型,否则你必须循环类型.

所以,在这里.

无符号很容易.min是所有位都是0的时候,最大值是所有位都是1的时候.

const unsigned type unsigned_type_min = (unsigned type)0;    
const unsigned type unsigned_type_max = ~(unsigned type)0;
Run Code Online (Sandbox Code Playgroud)

对于signed,min是在符号位置位但所有其他位都为零时,最大值是除了符号位之外的所有位都置位时.在不知道类型的大小的情况下,我们不知道符号位在哪里,但我们可以使用一些技巧来使其工作.

const signed type signed_type_max = (signed type)(unsigned_type_max >> 1);
const signed type signed_type_min = (signed type)(~(signed_type_max));
Run Code Online (Sandbox Code Playgroud)

对于浮点,有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.
   }
Run Code Online (Sandbox Code Playgroud)