Bit的思路是很自然而且紧凑的。
1.如果业务数固定,比如少于32项业务,那么一个32位的整型值足以表达:
定义枚举类型:
enum Business
{
BUSINESS_1 = 0x00000001;
BUSINESS_2 = 0x00000002;
BUSINESS_3 = 0x00000004;
BUSINESS_4 = 0x00000008;
BUSINESS_6 = 0x00000010;
BUSINESS_7 = 0x00000020;
...
BUSSNESI_32 = 0x80000000;
}
则可进行如下的组操作:
Business businessGroup = BUSINESS_1 | BUSINESS_6 | BUSINESS_23; // 创建一个业务组,包含了业务1,业务6和业务23
businessGroup |= BUSINESS_19; // 添加业务19至该业务组中
if (businessGroup & BUSINESS_21) ... // 判断业务21是否在该组中
businessGroup &= ~BUSINESS_6; // 从该组中删除业务6
businessGroup ^= BUSINESS_9; // “反转”操作:如果业务9在组中,则从组中删除之;否则将业务9加入组中。
businessGroup = 0; // 清空所有业务
businessGroup = ~0U; // 添加所有业务