Grails 按位运算符

发布于 2024-10-29 21:17:08 字数 384 浏览 4 评论 0原文

任何人都可以阐明我在 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 技术交流群。

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

发布评论

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

评论(2

婴鹅 2024-11-05 21:17:08

按位 & 运算符采用两个参数。如果这些参数中的任何一个为 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 of manager.memberOf) is 0.

旧城烟雨 2024-11-05 21:17:08

如果要设置一个位,则必须使用 OR 运算符(并集)。

def MANAGER = 0x04
manager.memberOf |= MANAGER

然后,当您想要检查标志是否已启用时,首先必须使用与 AND 运算符(交集)相同的掩码从字节中仅获取位,然后与掩码进行比较。如果与掩码相同,则该位已启用,如果为 0,则该位已禁用。

(manager.memberOf & MANAGER) == MANAGER

完整的工作示例:

def MANAGER = 1
def ADMIN = 2
def CLIENT = 4

def manager = [memberOf:0]

// Add to the MANAGER
manager.memberOf |= MANAGER


assert (manager.memberOf & MANAGER) == MANAGER
assert (manager.memberOf & ADMIN) == 0
assert (manager.memberOf & CLIENT) == 0​

If you want to set a bit, you have to use the OR operator (union).

def MANAGER = 0x04
manager.memberOf |= MANAGER

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.

(manager.memberOf & MANAGER) == MANAGER

Full working example:

def MANAGER = 1
def ADMIN = 2
def CLIENT = 4

def manager = [memberOf:0]

// Add to the MANAGER
manager.memberOf |= MANAGER


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