是否可以使用按位运算限制 int 值(设置范围)?
我需要让我的整数计数器以环绕方式具有从 1 到 6(含)的值。即从 1 开始,数到 6,然后返回到 1。我想知道是否可以使用某种按位逻辑来实现。当然,对于下面的 if 语句来说这是微不足道的,但我想知道一个衬里:)
int counter = 1;
for...
do something
if (counter++ == 7) counter = 1;
补充: 这就是为什么我想要 1 个衬垫:
byte output = (byte)((inputByte & 0xF8) | counter++);
I need to have my integer counter have values from 1 to 6 inclusive in wrap around fashion. Namely starting from 1, I count to 6 and go back to 1. I wonder if it's possible to achieve using some sort of bitwise logic. Of course it's trivial with if statement as below but I am wondering about one liner :)
int counter = 1;
for...
do something
if (counter++ == 7) counter = 1;
Addition:
Here is why I want 1 liner:
byte output = (byte)((inputByte & 0xF8) | counter++);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
使用模运算符。
要使用实数按位运算,您的模数必须是 2 的幂,但此处的情况并非如此。
PS:如果您的计数器从 0 而不是 1 开始,则不需要第二个
++counter
并且会编写类似以下内容的内容:PPS:请注意,通常
if
会执行不过,比模数更快。Use the modulo operator.
To use real bitwise operations your modulo must be a power-of-2 which is not the case here.
PS: If your counter started at 0 instead of 1, you wouldn't need the second
++counter
and would write something like :PPS: Note that generally an
if
performs faster than a modulo, tho.