Java中如何避免符号扩展位掩码?

发布于 2024-11-28 03:27:54 字数 160 浏览 1 评论 0原文

我的位掩码是字节,我想保持它们原样,但我认为它们是符号扩展的。我不在乎该字节被视为正数还是负数,只要它具有相同的位集即可。我只花了几个小时调试我的代码,然后我发现我的字节位掩码只有在它们恰好为负数时才出现问题,花了一段时间才发现。我不可能是唯一一个对此有问题的人。有没有办法让一个字节表现得像无符号的一样?

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

带上头具痛哭 2024-12-05 03:27:54

如果您不希望在算术(或按位)运算符中使用字节时对其进行符号扩展,则需要显式地按位和 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).

一花一树开 2024-12-05 03:27:54

你的代码中有右移吗?你用“>>”吗而不是“>>”?有你的问题。

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文