| Author |
Casting int value to Byte
|
Mohamed Alla Pitchai
Greenhorn
Joined: Oct 18, 2007
Posts: 12
|
|
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
Joined: Sep 06, 2005
Posts: 64
|
|
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
Joined: Oct 18, 2007
Posts: 12
|
|
|
Why do we want to do the 2's complement ?
|
 |
Rob Spoor
Sheriff
Joined: Oct 27, 2005
Posts: 19216
|
|
|
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.
|
SCJP 1.4 - SCJP 6 - SCWCD 5
How To Ask Questions How To Answer Questions
|
 |
praveen Shangunathan
Ranch Hand
Joined: Sep 06, 2005
Posts: 64
|
|
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
Joined: Jan 26, 2008
Posts: 23
|
|
|
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
Joined: Oct 27, 2005
Posts: 19216
|
|
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
Joined: Sep 15, 2007
Posts: 294
|
|
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
Joined: Jan 26, 2008
Posts: 23
|
|
|
Sorry my mistake i think i was wrong . Thanks for correcting me
|
 |
 |
|
|
subject: Casting int value to Byte
|
|
|