Narrowing type conversion in java -
this question has answer here:
- explicit conversion int byte in java 4 answers
i learning java , new programming. trying understand happening behind scenes in code:
short c = 234; byte d = (byte) c; system.out.println(d);
the output -22. can explain me magic happening behind scenes?
the number 234
in binary 11101010
.
although number fits in 8 bits, byte in java signed, largest possible byte value in java 127. , when significant (leftmost) bit set, means "negative number", number negative.
now, might wonder why number -22
when 1101010
not 22
. answer can found studying two's complement representation of numbers.
here wikipedia article it: https://en.wikipedia.org/wiki/two's_complement
Comments
Post a Comment