noogler
noogler

Reputation: 187

How is short 128 = byte -128 while explicit casting in java ?

import java.util.Scanner;

public class ShortToByte{
  public static void main (String args[]){
    int i=0;
    while (i<6){
      Scanner sinput = new Scanner (System.in);
      short a = sinput.nextShort();
      byte b = (byte) a;
      System.out.println("Short value : " + a + ",Byte value : " + b);
      i++;
    }
  }
}

I am trying to understand conversion between different data types, but I am confused as how is short value of 128 = -128 in byte and also how is 1000 in short = -24 in byte ?

I have been using the following logic to convert short to byte :

1000 in decimal -> binary = 0000 0011 1110 1000

while converting to byte : xxxx xxxx 1110 1000 which is equivalent to : 232

I do notice that the correct answer is the two's complement of the binary value, but then when do we use two's complement to convert and when not as while converting 3450 from short to byte I did not use two's complement yet achieved the desired result.

Thank you!

Upvotes: 0

Views: 697

Answers (2)

rgettman
rgettman

Reputation: 178303

Your cast from short to byte is a narrowing primitive conversion. The JLS, Section 5.1.3, states:

A narrowing conversion of a signed integer to an integral type T simply discards all but the n lowest order bits, where n is the number of bits used to represent type T. In addition to a possible loss of information about the magnitude of the numeric value, this may cause the sign of the resulting value to differ from the sign of the input value.

(bold emphasis mine)

Numeric types are signed in Java. The short 128, represented in bits as

00000000 10000000

is narrowed to 8 bits as follows:

10000000

... which is -128. Now the 1 bit is no longer interpreted as +128; now it's -128 because of how two's complement works. If the first bit is set, then the value is negative.

Something similar is going on with 1000. The short 1000, represented in bits as

00000011 11101000

is narrowed to 8 bits as follows:

11101000

... which is -24.

Upvotes: 5

Klaimmore
Klaimmore

Reputation: 690

From java datatypes:

  • 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)

Therefore 128 overflows to -128.

Upvotes: 1

Related Questions