2

In Java, why both (byte) 400000 and (byte) -400000 have result -128?

Actually, I followed the calculation method from https://stackoverflow.com/a/9085666/1037217

For case: 400000 Binary: 1100001101010000000 Trim to 8 digits: 10000000 Since the left most digit is 1, so -1 from it: 01111111 Then invert it: 10000000 Result: -128

For case: -400000 Binary: -1100001101010000000 Trim to 8 digits: 10000000 Since the left most digit is 1, so -1 from it: 01111111 Then invert it: 10000000 Result: 128

The same method works on (short) 40000 = -25536 (short) -40000 = 25536

Community
  • 1
  • 1
Felix
  • 31
  • 4
  • it's overflow. you can't store any of these number in byte variable. – Rustam Oct 23 '14 at 04:09
  • Suppose you gave them a different value. Now take some other pair of numbers, and do the same, and so on. Clearly you'd end up needing more than 256 different bytes, which is by definition impossible. – harold Oct 23 '14 at 12:26

3 Answers3

5

Casting an int to byte will preserve the int number's last 8 bits (the last byte).

 400000 = 0x61a80
-400000 = 0xfff9e580

Both of your numbers have the same last 8 bits: 0x80 which is -1 in 2's complement.

For example:

System.out.println((byte)0x23403); // Prints 3 (the last 8 bits: 0x03 = 3)
System.out.println((byte)0x23483); // Prints -125 (last 8 bits: 0x83 = -125)
// (in 2's complement: 0x83 = -(128-3) = -125)
icza
  • 389,944
  • 63
  • 907
  • 827
  • Sorry, I added some examples, can you explain them? – Felix Oct 23 '14 at 04:58
  • @Felix Just take the last 8 bits. Simple. If you want to understand what number the bits will give you, you need to read about and understand [2's complement](http://stackoverflow.com/questions/1049722/what-is-2s-complement). – icza Oct 23 '14 at 05:03
2

Because byte has the range -128 to 127. Both of your values overflow and are then subject to a narrowing conversion. To quote JLS Example 5.1.3-2. Narrowing Primitive Conversions that lose information,

// An int value too big for byte changes sign and magnitude:
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
0

As you say:

For case: 400000 Binary: 1100001101010000000 Trim to 8 digits: 10000000 Since the left most digit is 1, so -1 from it: 01111111 Then invert it: 10000000 Result: -128

For case: -400000 Binary: -1100001101010000000 Trim to 8 digits: 10000000 Since the left most digit is 1, so -1 from it: 01111111 Then invert it: 10000000 Result: 128

In both cases, the bit pattern you get is 10000000. That equates to -128 both times. A byte cannot represent the value 128; it is out of range.

However, your procedure is not quite right. You can't just put a negative sign there and then "trim to 8 digits". A negative sign is not a valid state for a bit. You should probably study the 2s complement representation of integers.

Community
  • 1
  • 1
Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153