我总是记不住电话号码。我需要一个记忆规则。


当前回答

永远不要忘记任何类型的最大值:

如果它有32位,最大的可能值将是带有数字1的32位:

结果将是十进制的4294967295:

但是,由于也有负数的表示,4294967295除以2,得到2147483647。

因此,一个32位整数能够表示-2147483647到2147483647

其他回答

永远不要忘记任何类型的最大值:

如果它有32位,最大的可能值将是带有数字1的32位:

结果将是十进制的4294967295:

但是,由于也有负数的表示,4294967295除以2,得到2147483647。

因此,一个32位整数能够表示-2147483647到2147483647

最简单的方法是查看std::numeric_limits< int >::max()

例如(来自MSDN),

// numeric_limits_max.cpp

#include <iostream>
#include <limits>

using namespace std;

int main() {
   cout << "The maximum value for type float is:  "
        << numeric_limits<float>::max( )
        << endl;
   cout << "The maximum value for type double is:  "
        << numeric_limits<double>::max( )
        << endl;
   cout << "The maximum value for type int is:  "
        << numeric_limits<int>::max( )
        << endl;
   cout << "The maximum value for type short int is:  "
        << numeric_limits<short int>::max( )
        << endl;
}

大约是2.1 * 10^9。不需要知道确切的2^{31}- 1 = 2,147,483,647。

C

你可以在C语言中找到它:

#include <stdio.h>
#include <limits.h>

main() {
    printf("max int:\t\t%i\n", INT_MAX);
    printf("max unsigned int:\t%u\n", UINT_MAX);
}

给出(好吧,没有,)

max int:          2,147,483,647
max unsigned int: 4,294,967,295

C + 11 +

std::cout << std::numeric_limits<int>::max() << "\n";
std::cout << std::numeric_limits<unsigned int>::max() << "\n";

Java

你也可以用Java得到这个:

System.out.println(Integer.MAX_VALUE);

但是请记住,Java整数总是有符号的。

Python 2

Python有任意的精确整数。但在python2中,它们被映射为C整数。所以你可以这样做:

import sys
sys.maxint
>>> 2147483647
sys.maxint + 1
>>> 2147483648L

所以当整数大于2^31 -1时,Python会切换为long

2^(x+y) = 2^x * 2^y

2^10 ~ 1,000
2^20 ~ 1,000,000
2^30 ~ 1,000,000,000
2^40 ~ 1,000,000,000,000
(etc.)

2^1 = 2
2^2 = 4
2^3 = 8
2^4 = 16
2^5 = 32
2^6 = 64
2^7 = 128
2^8 = 256
2^9 = 512

2^31 (signed int max)等于2^30(约10亿)乘以2^1(2)也就是20亿。2^32等于2^30 * 2^2,大约是40亿。这种近似方法甚至可以精确到2^64左右(误差增长到15%左右)。

如果你需要一个确切的答案,那么你应该打开计算器。

方便的字对齐容量近似:

2^16 ~= 64千// uint16 2^32 ~= 40亿// uint32, IPv4, unixtime 2^64 ~= 16 quintillion(又名160亿billion或1600万trillion) // uint64, "bigint" 2^128 ~= 256quintillion quintillion(又名256trillion trillion万亿)// IPv6, GUID

一般来说,你可以做一个简单的操作,它反映了Int32的本质,用1填充所有可用的位-这是你可以很容易地保存在你的内存中的东西。它在大多数语言中的工作方式基本相同,但我以Python为例:

max = 0
bits = [1] * 31 # Generate a "bit array" filled with 1's
for bit in bits:
    max = (max << 1) | bit
# max is now 2147483647

对于unsigned Int32,将其设置为32而不是31个1。

但因为有一些更冒险的方法,我开始考虑公式,只是为了好玩…

公式1(如果没有给出运算符,则将数字连在一起)

a = 4 b = 8 巴/ a ab-1 接 ab-a-b ab-1

Python quickcheck

a = 4
b = 8
ab = int('%d%d' % (a, b))
ba = int('%d%d' % (b, a))
'%d%d%d%d%d' % (ba/a, ab-1, ab, ab-a-b, ab-1)
# gives '2147483647'

公式2

X = 48 x / 2 - 3 x - 1 x x * 3/4 x - 1

Python quickcheck

x = 48
'%d%d%d%d%d' % (x/2-3, x-1, x, x*3/4, x-1) 
# gives '2147483647'