wood burning stoves
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
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "problem in bitwise and" Watch "problem in bitwise and" New topic

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,
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 15081

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 8 API documentation
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
I agree. Here's the link: http://aspose.com/file-tools
subject: problem in bitwise and
It's not a secret anymore!