为什么int的范围是-1? [英] Why does the range of int has a minus 1?

查看:807
本文介绍了为什么int的范围是-1?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我读到int的范围取决于一个字节。

I read that the range of an int is dependent on a byte.

因此将int设为4个字节长,即4 * 8位= 32位。

So taking int to be 4 bytes long, thats 4 * 8 bits = 32 bits.

所以范围应该是:2 ^(32-1)= 2 ^(31)

So the range should be : 2 ^ (32-1) = 2 ^ (31)

为什么有人说它2 ^ 31 - 1虽然?

Why do some people say its 2^31 - 1 though?

谢谢!

推荐答案

因为计数从0开始

并且int的范围是 2,147,483,647 2 ^ 32 这是 2,147,483,648 。因此我们减去 1

And the range of int is 2,147,483,647 and 2^32 which is 2,147,483,648. hence we subtract 1

此外,1位的损失是正负号

Also the loss of 1 bit is for the positive and negative sign

wiki 关于整数的文章中检查此兴趣: -

Check this interestinf wiki article on Integers:-


正整数的最常见表示是使用二进制数字系统的
位字符串。存储位的存储器字节
的顺序是变化的;看到字节序。
整数类型的宽度或精度是其表示中的位数。具有n位的整数
类型可以编码2n个数字;例如,无符号类型
通常表示非负值0到2n-1。有时使用其他
编码的整数值到位模式,对于
示例二进制编码的十进制或格雷码,或打印字符
代码,如ASCII。

The most common representation of a positive integer is a string of bits, using the binary numeral system. The order of the memory bytes storing the bits varies; see endianness. The width or precision of an integral type is the number of bits in its representation. An integral type with n bits can encode 2n numbers; for example an unsigned type typically represents the non-negative values 0 through 2n−1. Other encodings of integer values to bit patterns are sometimes used, for example Binary-coded decimal or Gray code, or as printed character codes such as ASCII.

在二进制
计算系统中有四种众所周知的方法来表示有符号数。最常见的是二进制补码,它允许带有n位的
有符号整数类型来表示从-2(n-1)
到2(n-1)-1的数字。二进制补码算法很方便,因为
表示
和值之间存在完美的一对一对应关系(特别是没有单独的+0和-0),并且因为
加法,减法和乘法不需要区分有符号和无符号类型之间的
。其他可能性包括偏移
二进制,符号幅度和1补码。

There are four well-known ways to represent signed numbers in a binary computing system. The most common is two's complement, which allows a signed integral type with n bits to represent numbers from −2(n−1) through 2(n−1)−1. Two's complement arithmetic is convenient because there is a perfect one-to-one correspondence between representations and values (in particular, no separate +0 and −0), and because addition, subtraction and multiplication do not need to distinguish between signed and unsigned types. Other possibilities include offset binary, sign-magnitude, and ones' complement.

这篇关于为什么int的范围是-1?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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