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

查看:76
本文介绍了为什么 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,6472^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),并且因为加减乘法不需要区分在有符号和无符号类型之间.其他可能性包括偏移二进制、符号大小和一个的补码.

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天全站免登陆