gpt4 book ai didi

java - 如何简化将几个 boolean 对象表示为位序列?

转载 作者:行者123 更新时间:2023-11-30 08:09:42 26 4
gpt4 key购买 nike

考虑选择一周中的几天,我们可以选择一天、几天或什么都不选。
我正在尝试按如下方式存储该数据:

public static final int NONE = 0b0000000;
public static final int MONDAY = 0b0000001;
public static final int TUESDAY = 0b0000010;
public static final int WEDNESDAY = 0b0000100;
public static final int THURSDAY = 0b0001000;
public static final int FRIDAY = 0b0010000;
public static final int SATURDAY = 0b0100000;
public static final int SUNDAY = 0b1000000;

其中0是NONE,11是MONDAY和TUESDAY,1000011是MONDAY,TUESDAY和SUNDAY;
有没有办法,我可以以更具可读性的方式编写相同的内容?

编辑:enums 的使用在 dalvik(android jvm)中有不错的性能惩罚,请不要建议它们。

最佳答案

我认为这与您正在尝试做的类似。

    public static final int NONE = 0;
public static final int MONDAY = 1;
public static final int TUESDAY = 2;
public static final int WEDNESDAY = 4;
public static final int THURSDAY = 8;
public static final int FRIDAY = 16;
public static final int SATURDAY = 32;
public static final int SUNDAY = 64;

public static void main(String[] args) {

int z = Integer.MAX_VALUE ^ SUNDAY ^ MONDAY;
for (int x = 1; x <= 64; x = x * 2) {
System.out.println(z & x);
}
}

输出

0
2
4
8
16
32
0

关于java - 如何简化将几个 boolean 对象表示为位序列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32227606/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com