位移位运算符在 C# 中有效,但定义宏不可用。
要了解发生了什么,您可以做的是分别计算这些值,然后将它们放入枚举中。
当然你知道那|
是按位或运算符。以防万一操作员<<
将二进制文件向左移动:
1 << 16 = 10000000000000000_2 //those are 16 zeroes and _2 indicates binary
反过来:
10000000000000000_2 = 65536
这相当于将数字乘以第二个操作数指示的次数。
1 << 1 = 2
1 << 2 = 4
1 << 3 = 8
没错,就是将数字乘以 2 的幂:
1 << 1 <=> 1 * 2^1 = 2
1 << 2 <=> 1 * 2^2 = 4
1 << 3 <=> 1 * 2^3 = 8
现在,从那时FOO_1 = 0
起
DISP_1 = MASK(FOO_1)
=>
DISP_1 = ((1 << 16) | (FOO_1))
=>
DISP_1 = (65536 | (FOO_1))
=>
DISP_1 = (65536 | FOO_1)
=>
DISP_1 = (65536 | 0)
=>
DISP_1 = 65536
做同样的FOO_2
事情,我取值为 1 会给你:
DISP_2 = (65536 | FOO_2)
=>
DISP_2 = (65536 | 1)
=>
DISP_2 = 65537
话虽如此,以下工作正常:
enum FOO
{
FOO_1 = 0,
FOO_2,
// etc
}
enum DISP
{
DISP_1 = (1<<16) | (int)(FOO.FOO_1),
DISP_2 = (1<<16) | (int)(FOO.FOO_2),
// etc
}