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 with this. Is there a way to make a byte behave as if it was unsigned?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您不希望在算术(或按位)运算符中使用字节时对其进行符号扩展,则需要显式地按位和 0xFF。它看起来有点难看,但如果你拥有的是字节,这是不可避免的(并且希望一个像样的 JIT 能够识别该习惯用法并从中生成有效的代码)。
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.