Arnab Das Arnab Das - 2 months ago 7
Scala Question

Scala Byte type can contain -128 but not 128

I'm new to Scala. I've encountered a strange fact that it's

Byte
type can contain -128 but not 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


Apparently it feels that, to indicate a negative number, first flag is used. For positive numbers also this flag is reserved. This is understandable. But, why one more negative number than the positives.

Answer

Because that's 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).

As explained, this is because of Two's Complement.

Let's explain a bit more. A byte holds 8 bits, and if we wanted to represent the number -128. We start from 128:

10000000

And we invert the bits:

01111111

And add 1. We get back:

10000000

This is how -128 is represented. This means that the biggest signed number we can represent with Twos Complement is:

0111111

Which is equivalent to 127.

From wikipedia:

An N-bit two's-complement numeral system can represent every integer in the range −(2N − 1) to +(2N − 1 − 1)

So, we have:

-(2^7-1) = (-128) to +(2^7-1 - 1) = +(127)