programming forums Java Java JSRs Mobile Certification Databases Caching Books Engineering OS Languages Frameworks Products This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
Sheriffs:
Saloon Keepers:
Bartenders:

# Casting int value to Byte

Mohamed Alla Pitchai
Greenhorn
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.

Thanks,
Mohamed

praveen Shangunathan
Ranch Hand
Posts: 65
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
Why do we want to do the 2's complement ?

Rob Spoor
Sheriff
Posts: 21092
85
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
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
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
Posts: 21092
85
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
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
Sorry my mistake i think i was wrong . Thanks for correcting me