Scala 字节类型可以包含 -128 但不能包含 128
Scala Byte type can contain -128 but not 128
我是 Scala 新手。我遇到了一个奇怪的事实,它的 Byte
类型可以包含 -128 但不能包含 128.
scala> val overflow1NegByte = -129:Byte
<console>:11: error: type mismatch;
found : Int(-129)
required: Byte
val overflow1NegByte = -129:Byte
^
scala> val overflow1NegByte = -128:Byte
overflow1NegByte: Byte = -128
scala> val overflow1PosByte = 128:Byte
<console>:11: error: type mismatch;
found : Int(128)
required: Byte
val overflow1PosByte = 128:Byte
^
scala> val overflow1PosByte = 127:Byte
overflow1PosByte: Byte = 127
貌似感觉,要表示负数,先用flag。对于正数也保留此标志。这是可以理解的。但是,为什么负数比正数多一个。
因为那是 the range of a Byte
on the JVM:
byte
: The byte data type is an 8-bit signed two's complement integer.
It has a minimum value of -128 and a maximum value of 127 (inclusive).
如前所述,这是因为 Two's Complement。
让我们再解释一下。一个字节包含 8 位,如果我们要表示数字 -128。我们从 128:
开始
10000000
然后我们反转位:
01111111
并加1。我们得到:
10000000
-128 是这样表示的。这意味着我们可以用二进制补码表示的最大有符号数是:
01111111
相当于127。这与二进制补码使用MSB(最高有效位)表示符号的事实一致。
来自wikipedia:
An N-bit two's-complement numeral system can represent every integer
in the range −(2N − 1) to +(2N − 1 − 1)
所以,我们有:
-(2^7-1) = (-128) to +(2^7-1 - 1) = +(127)
我是 Scala 新手。我遇到了一个奇怪的事实,它的 Byte
类型可以包含 -128 但不能包含 128.
scala> val overflow1NegByte = -129:Byte
<console>:11: error: type mismatch;
found : Int(-129)
required: Byte
val overflow1NegByte = -129:Byte
^
scala> val overflow1NegByte = -128:Byte
overflow1NegByte: Byte = -128
scala> val overflow1PosByte = 128:Byte
<console>:11: error: type mismatch;
found : Int(128)
required: Byte
val overflow1PosByte = 128:Byte
^
scala> val overflow1PosByte = 127:Byte
overflow1PosByte: Byte = 127
貌似感觉,要表示负数,先用flag。对于正数也保留此标志。这是可以理解的。但是,为什么负数比正数多一个。
因为那是 the range of a Byte
on the JVM:
byte
: The byte data type is an 8-bit signed two's complement integer. It has a minimum value of -128 and a maximum value of 127 (inclusive).
如前所述,这是因为 Two's Complement。
让我们再解释一下。一个字节包含 8 位,如果我们要表示数字 -128。我们从 128:
开始10000000
然后我们反转位:
01111111
并加1。我们得到:
10000000
-128 是这样表示的。这意味着我们可以用二进制补码表示的最大有符号数是:
01111111
相当于127。这与二进制补码使用MSB(最高有效位)表示符号的事实一致。
来自wikipedia:
An N-bit two's-complement numeral system can represent every integer in the range −(2N − 1) to +(2N − 1 − 1)
所以,我们有:
-(2^7-1) = (-128) to +(2^7-1 - 1) = +(127)