• Post Reply Bookmark Topic Watch Topic
  • New Topic

Trying to understand Casting  RSS feed

 
Chad McAte
Greenhorn
Posts: 11
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
why does this result in -128?
int a = 128;
byte b = 0;
b =(byte) a;

why does this result in 44
int a = 300;
byte b = 0;
b =(byte) a;

I think I understand the fact that you wouldn't cast this way. Just trying to understand the output. If I am correct you would use casting when you have something like this
               int a = 50;
               byte b = 0;
               b = (byte) a * 2;
Although 50 * 2 = 100 which is in the range of byte, the use of the operator automatically converts the expression to an interger. Thanks for whatever you care share.


 
Henry Wong
author
Sheriff
Posts: 23295
125
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Chad McAte wrote:why does this result in -128?
int a = 128;
byte b = 0;
b =(byte) a;


The bit pattern for a 128 value int is ... 0000 0000 0000 0000 0000 0000 1000 0000. When you explicitly cast it to a byte, even though this value doesn't fall into the range of the byte, the compiler will use the same bit pattern (for the lower 8 bits only).  And under twos complement rules, the bit pattern of 1000 0000, as a byte is -128.

Henry
 
Henry Wong
author
Sheriff
Posts: 23295
125
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Chad McAte wrote:
why does this result in 44
int a = 300;
byte b = 0;
b =(byte) a;


The bit pattern for a 300 value int is ... 0000 0000 0000 0000 0000 0001 0010 1100. When you explicitly cast it to a byte, even though this value doesn't fall into the range of the byte, the compiler will use the same bit pattern (for the lower 8 bits only).  And under twos complement rules, the bit pattern of 0010 1100, as a byte is 44.

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