要设置一点,请使用:
x |= 0b1; // set LSB bitx |= 0b10; // set 2nd bit from LSB
擦除一下使用:
x &= ~0b1; // unset LSB bit (if set)x &= ~0b10; // unset 2nd bit from LSB
切换一下用途:
x ^= 0b1;
请注意,我使用0b?。您也可以使用任何整数,例如:
x |= 4; // sets 3rd bitx |= 0x4; // sets 3rd bitx |= 0x10; // sets 9th bit
但是,这使得更难知道正在更改哪个位。
使用二进制可让您查看将要设置/擦除/切换的确切位。
要动态设置位,请使用:
x |= (1 << y); // set the yth bit from the LSB
(1 << y)将… 001 y个位左移,因此您可以将设置的y个位移动。
您还可以一次设置多个位:
x |= (1 << y) | (1 << z); // set the yth and zth bit from the LSB
或取消设置:
x &= ~((1 << y) | (1 << z)); // unset yth and zth bit
或切换:
x ^= (1 << y) | (1 << z); // toggle yth and zth bit



