• Post Reply Bookmark Topic Watch Topic
  • New Topic

Narrowing conversion  RSS feed

 
Vibhor Chander
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Q. I am not able to understand why the output is -126.

 
Henry Wong
author
Sheriff
Posts: 23295
125
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Unfortunately, to understand this, you need to understand the twos complement format ... but... basically, 130 as a long is this in binary...

130 => 00000000 00000000 00000000 00000000 00000000 00000000 00000000 10000010

To cast to a byte (narrowing), Java simply truncates to ... 10000010 ... and in twos complement format, that is equal to -126. The reason this happened is because 130 is outside of the range of byte, and the binary (after truncate) actually has the sign bit on (set to one).

Henry
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!