Collectives™ on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
Learn more about Collectives
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
Learn more about Teams
short a = sinput.nextShort();
byte b = (byte) a;
System.out.println("Short value : " + a + ",Byte value : " + b);
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!
–
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
.
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.
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.