Question

The Java data type byte for example holds data from -128 to 127 in a single byte on storage. To enable to distingush between - 1 to -128 from 0 to 127 would require extra data which would take the datatype obver its allocated storage. Admittedly it would only take 1 extra bit but it still goes over.

How does java do this?

Was it helpful?

Solution

Two's complement:

The primitive types are defined to be the same on all machines and in all implementations, and are various sizes of two's-complement integers, single- and double-precision IEEE 754 standard floating-point numbers, a boolean type, and a Unicode character char type. —The Java Language Specification: Introduction

You can imagine it as an integer from 0 to 255 from which 128 is always subtracted.

More technical: an integer can (and will) be negated (positive → negative or vice versa) by inverting its bits and adding one. This is almost like One's complement (which simply inverts all bits—hence complement. But one's complement has the problem that it has two different zeroes: +0 and −0 (floating-point numbers have that too, but for other reasons and more useful ☺). Two's complement solves this by adding one, and thereby extending the range of negative values (that's why it's −128..127).

In some way you could say that the sign is indeed "stored" in the first bit of the number. So your observation that it needs one bit of storage is correct. But the numeric range of a byte (positive or negative, ignoring the sign) only needs 7 bits, so you have a byte again.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top