File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes (byte) and 0xff Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "(byte) and 0xff" Watch "(byte) and 0xff" New topic

(byte) and 0xff

Stefan Geelen
Ranch Hand

Joined: Nov 19, 2001
Posts: 49
can someone explain to me what happens with following:
byte blue = (byte)0x98;
System.out.println("blue: "+ (byte) blue);
System.out.println("blue2: "+ ( ((byte) blue) & 0xff));
The print result is -104
The second + 152
Why does the 0xff makes the bytes a unsigned byte ?
Can someone tell me an online reference where I can learn more about basic bit and bytes calculation ?
Dave Landers
Ranch Hand

Joined: Jul 24, 2002
Posts: 401
The result of the operation ((byte) blue) & 0xff is an int, not a byte.
Note that 0xff is an int, and so byte & int = int.
Try again with (byte)blue & (byte)0xff
Dirk Schreckmann

Joined: Dec 10, 2001
Posts: 7023
Just in case the reasoning behind why the result was positive isn't quite yet clear...
Note that when you cast the int result to a byte, the high-order (left-most) bits were lost. The left-most bit specifies whether the integral value is positive or negative.
For further example, the int value 129 in bits is
0000 0000 0000 0000 0000 0000 1000 0001
If this int value were cast to a byte, the result would be to chop of (and feed to the cat - see Cat and Mouse Games with Bits) the left-most bits
1000 0001
which is -127.
I haven't yet compiled a list of easy-to-read-and-understand explanations on bit manipulations (aside from the aforementioned campfire story). In the past, I've had success finding decent explanations by searching on Google.
Good Luck.

[How To Ask Good Questions] [JavaRanch FAQ Wiki] [JavaRanch Radio]
I agree. Here's the link:
subject: (byte) and 0xff
jQuery in Action, 3rd edition