And
value 10101010 &mask 11110000result 1010
the ability to extract bytes or nibbles(half byte) or any other positional subset of bits is one of the key uses of the bitwise AND operator.
Right Shift
(0b110111000001010000111100 &0b111111110000000000000000) >> 16result 0b1101110
Hexadecimal number
each binary nibble can be in 1 of 16 stats
Binary000000010010001101000101011110001001101010111100110111101111
1101 1100 0001 0100 0011 1100
D C 1 4 3 C
Left Shift
extract middle byte of dc143c
1 byte = 8 bit
(0xdc143c & (0xff << 8)) >> 80xdc143c 0b1101 1100 0001 0100 0011 11000xff << 8 0b 1111 1111 0000 0000result 0b 0001 0100 0000 0000>> 8result 0b 0001 01000x 1 4
Integer packed bits
cleaing bits with an inverse mask
value 10101010 &mask 11110111result 10100010

Exclusive or
either but not both of the corresponding bits in the operands are set,the result is cleared if they are the same, bitwize exclusive or can be thought of as bitwize not equal
it can be used to toggle 0 to 1 and 1 to 0
value 10101010 ^mask 01100111result 11000101
bits = 0b1010mask = 0b0111bits ^= mask0b1101
Bitwize Complement
~0b111100000b0000
计算 align
// 对齐到ALIGNMENT, ALIGNMENT必须是2的n次方,也就是binary 0b100 0b1000 0b10000pub fn align_to_size(size: usize) -> usize {if size & (ALIGNMENT - 1) == 0 {return size;}size + (ALIGNMENT - (size & (ALIGNMENT - 1)))}假如 ALIGNMENT = 88 = 1000ALIGNMENT - 1 = 77 = 0111// size & (ALIGNMENT - 1) == 0这个说明,只要size是ALIGNMENT的倍数,这个等式成立16 = 1000024 = 1100040 = 101000否则会返回除ALIGNMENT的余数
set bit & clear bit
a |= (1 << n) // set bitb &= ~(1<<n) // clear bitc ^= (1 << n) // toggle bit
void binary(unsigned int n) {for (int i = 256; i > 0; i /= 2) {if (n & i) {printf(" 1");} else {printf(" 0");}}printf("\n");}
left/right most
right = val & 0xffleft = (val >> 8) & 0xff
get n bits from position p
unsigned getbits(unsigned x, int p, int n) {return (x >> (p + 1 - n)) & ~(~0 << n);}
分析: b = getbits(208, 6, 3) ==> 5
208 ==> 1101 0000
因为position是从0开始,第6位position是第7个数字, 所以将 1101 0000 右移4位 变成 1101,~0 按位取反得到的是 -1 ,(~0 << n) 是 n 个 1 也就是 1000, 再取反,变成 0111 在于 1101 与运算 后得到 101, 也就是第6位后3位
