• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Tim Cooke
  • Ron McLeod
  • Jeanne Boyarsky
  • Paul Clapham
Sheriffs:
  • Liutauras Vilda
  • Henry Wong
  • Devaka Cooray
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • Al Hobbs
  • Carey Brown
Bartenders:
  • Piet Souris
  • Mikalai Zaikin
  • Himai Minh

(byte) and 0xff

 
Ranch Hand
Posts: 49
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
 
Ranch Hand
Posts: 401
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
 
Sheriff
Posts: 7023
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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.
 
reply
    Bookmark Topic Watch Topic
  • New Topic