开发者

How to avoid sign extending bit mask in Java?

My bit masks are bytes, and I'd like to keep them exactly as they are, but I think they're sign extended. I don't care if the byte is considered positive or negative, as long as it has the same bits set. I just spent a few hours debugging my code, and then I found I'm only having a problem with my byte bit masks when they happen to be negative, it took a while to find out. I can't be the only one who's had a problem wit开发者_运维问答h this. Is there a way to make a byte behave as if it was unsigned?


If you don't want a byte to sign extend when you use it in arithmetic (or bitwise) operators, you need to explicitly bitwise-and it with 0xFF. It looks slightly ugly but is unavoidable if what you have is a byte (and hopefully a decent JIT will be able to recognize the idiom and make efficient code out of it anyway).


Do you have right-shift in your code? do you use '>>' instead of '>>>'? There is your problem.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜