Win a copy of Cross-Platform Desktop Applications: Using Node, Electron, and NW.js this week in the JavaScript forum!
programming forums Java Java JSRs Mobile Certification Databases Caching Books Engineering Languages Frameworks Products This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
Sheriffs:
Saloon Keepers:
Bartenders:

# (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.