• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Casting int value to Byte

 
Mohamed Alla Pitchai
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello guys,
Consider the following code snippet.

int x = 241;
byte y = (byte) x;

System.out.println("y is " + y);

I am getting the output as -15. How did the result come as -15.
Please explain.

Thanks,
Mohamed
 
praveen Shangunathan
Ranch Hand
Posts: 65
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
byte can take only 8 bits with the 8th bit for sign(+ or -)
241 = 11110001
2's complement of 1110001 is 1111 which is 15.
 
Mohamed Alla Pitchai
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Why do we want to do the 2's complement ?
 
Rob Spoor
Sheriff
Pie
Posts: 20494
54
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You don't, it's just easy to determine the value of a negative binary number. If the two's complement is 15, the value is -15.
 
praveen Shangunathan
Ranch Hand
Posts: 65
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thats the way -ve numbers are represented.
if the 8th bit is 0 then its a +ve number and you "convert" the remaining 7 bits to find the integer value.
if the 8th bit is 1 then we are looking at a -ve number. so you 2's complement the remaining 7 bits, get
integer value and put a - in front.
 
Manish Khurana
Greenhorn
Posts: 23
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
you do not actually need to cast to byte in your assignment. Let Mr compiler sweat it out and do some thing worthwhile for qa change except for pointing your errors. it does same for char and short (downcasts).
 
Rob Spoor
Sheriff
Pie
Posts: 20494
54
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Manish Khurana:
you do not actually need to cast to byte in your assignment.

Yes you do.

For bytes, you can only assign literals and constants between -128 and 127. Any other number, you need an explicit cast.
 
Doug Slattery
Ranch Hand
Posts: 294
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
you do not actually need to cast to byte in your assignment.

You also need the cast because you are downcasting from an int to a byte (a bigger bucket to a smaller). You don't need the cast going the other way (byte to int).

Aloha,
Doug

-- Nothing is impossible if I'mPossible
 
Manish Khurana
Greenhorn
Posts: 23
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Sorry my mistake i think i was wrong . Thanks for correcting me
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic