Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Confusion

 
Priya Jotwani
Ranch Hand
Posts: 53
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
When I try to print the value of z, it gives 64 as result .Can anyone plz tell why ??
byte x=64;
byte y=5;
byte z= (byte)(x*y);
 
Bhushan Jawle
Ranch Hand
Posts: 249
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ideally with proper data type you should get 320 as answer but as it exceeds the capacity of a byte most significant bits (MSB) in binary representation is chopped of . Amount decimal reprn. of remaining bits is 64.
i.e. 101000000 is 320 but if you try to fit that in byte first 10 is chopped of so you get 1000000 which is 64 in dec.
 
Vijayakumar Arya
Ranch Hand
Posts: 76
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
64 is getting printed correctly. Let me explain how,
z = 64 * 5 = 320 == 0x140
You are doing a type conversion (narrowing) on z, this drops the higher order bytes and takes only upto the bytes specified for the datatype,
byte - 1 byte
short - 2 bytes
int - 4 bytes
(byte)0x140 = 0x40 = 64 in decimal, so 64 is getting printed.
----------------------------
vijay
 
Priya Jotwani
Ranch Hand
Posts: 53
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanx Bhushan!!
 
Consider Paul's rocket mass heater.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic