And
value 10101010 &
mask 11110000
result 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) >> 16
result 0b1101110
Hexadecimal number
each binary nibble can be in 1 of 16 stats
Binary
0000
0001
0010
0011
0100
0101
0111
1000
1001
1010
1011
1100
1101
1110
1111
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)) >> 8
0xdc143c 0b1101 1100 0001 0100 0011 1100
0xff << 8 0b 1111 1111 0000 0000
result 0b 0001 0100 0000 0000
>> 8
result 0b 0001 0100
0x 1 4
Integer packed bits
cleaing bits with an inverse mask
value 10101010 &
mask 11110111
result 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 01100111
result 11000101
bits = 0b1010
mask = 0b0111
bits ^= mask
0b1101
Bitwize Complement
~0b11110000
0b0000
计算 align
// 对齐到ALIGNMENT, ALIGNMENT必须是2的n次方,也就是binary 0b100 0b1000 0b10000
pub fn align_to_size(size: usize) -> usize {
if size & (ALIGNMENT - 1) == 0 {
return size;
}
size + (ALIGNMENT - (size & (ALIGNMENT - 1)))
}
假如 ALIGNMENT = 8
8 = 1000
ALIGNMENT - 1 = 7
7 = 0111
// size & (ALIGNMENT - 1) == 0
这个说明,只要size是ALIGNMENT的倍数,这个等式成立
16 = 10000
24 = 11000
40 = 101000
否则会返回除ALIGNMENT的余数
set bit & clear bit
a |= (1 << n) // set bit
b &= ~(1<<n) // clear bit
c ^= (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 & 0xff
left = (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位