This week's book giveaways are in the Refactoring and Agile forums.We're giving away four copies each of Re-engineering Legacy Software and Docker in Action and have the authors on-line!See this thread and this one for details.
Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!

# (byte) and 0xff

Stefan Geelen
Ranch Hand
Posts: 49
Hi,
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 ?
Regards,
Stefan

Dave Landers
Ranch Hand
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
Sheriff
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.