Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

problem in bitwise and

 
thejaswini ramesh
Ranch Hand
Posts: 74
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 15272
37
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
thejaswini ramesh
Ranch Hand
Posts: 74
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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?
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic