Grails 按位运算符
任何人都可以阐明我在 Grails(或 groovy,就此而言)中的按位运算符的问题吗?
我正在尝试使用带有标志的域类属性,这是我到目前为止所尝试的 - 它们都不起作用:
manager.memberOf &= 0x04
manager.memberOf = manager.memberOf & 0x04
manager.memberOf = manager.memberOf.and(0x04)
有什么想法吗?我完全不知道...
TIA, sphere
ps:manager.memberOf 是 Integer 类型,默认值为 0(零)
ps2:memberOf 在执行任何这些操作后仍为零
can anybody shed some light on my problem with bitwise operators in Grails (or groovy, for that matter)?
I'm trying to use a domain class property with flags and here's what I've tried so far - none of them work:
manager.memberOf &= 0x04
manager.memberOf = manager.memberOf & 0x04
manager.memberOf = manager.memberOf.and(0x04)
any ideas? I'm totally clueless...
TIA,
sphere
ps: manager.memberOf is an Integer type and has a default value of 0 (zero)
ps2: memberOf remains zero after any of these operations
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
按位
&
运算符采用两个参数。如果这些参数中的任何一个为 0,则结果将为零。在您的情况下,结果始终为 0,因为参数之一(manager.memberOf
的初始值)为 0。The bitwise
&
operator takes two arguments. If any of these arguments is 0, the result will be zero. In your case the result is always 0 because one of the arguments (the initial value ofmanager.memberOf
) is 0.如果要设置一个位,则必须使用 OR 运算符(并集)。
然后,当您想要检查标志是否已启用时,首先必须使用与 AND 运算符(交集)相同的掩码从字节中仅获取位,然后与掩码进行比较。如果与掩码相同,则该位已启用,如果为 0,则该位已禁用。
完整的工作示例:
If you want to set a bit, you have to use the OR operator (union).
then, when you want to check if a flag is enabled, first you have to get only the bit from the byte using the same mask with the AND operator (intersection) and compare with the mask. If it's the same as the mask, the bit was enabled, if it's 0, the bit was disabled.
Full working example: