This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes problem in bitwise and Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "problem in bitwise and" Watch "problem in bitwise and" New topic
Author

problem in bitwise and

thejaswini ramesh
Ranch Hand

Joined: Oct 19, 2005
Posts: 74
Hi everyone,

I have a problem with bitwise anding.

1 & 0xff gives me 1
but 254 & 0xff gives me -2

What am I missing here, because I need to display as 254 (not -2)after masking with ff?

Thanks in advance,
Thejaswini.
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 14074
    
  16

Can you show us the code that gives -2 when you do 254 & 0xff?

Are you putting the result in a byte? Notice that the range of possible values for the data type byte is -128 to 127. The number 254 doesn't fit in a byte. A byte with the bit pattern 11111110 is interpreted as -2 instead of 254.


Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 7 API documentation
Scala Notes - My blog about Scala
thejaswini ramesh
Ranch Hand

Joined: Oct 19, 2005
Posts: 74
Thanks Jesper!

Yes am assigning the result of (254 & 0xff) to a byte. But I need the value as a byte since am writing it to an output stream.
Stan James
(instanceof Sidekick)
Ranch Hand

Joined: Jan 29, 2003
Posts: 8791
Java's lack of an unsigned byte bugs me. I used to enjoy using 0..255 in Pascal. I usually do these bitwise operations in ints (taking care to only use the low 8 bits) then convert to byte only if necessary. At least I can see a value like 254 when I want to.

When you see -2 I bet the right bits are still going to the stream, no?


A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
 
subject: problem in bitwise and
 
Similar Threads
NX:[URLyBird]How to use the specified Data File Format?
Corrupt file name after compression.
hexadecimal problem
Usage of non-shortcutting operators
Converting