And

  1. value 10101010 &
  2. mask 11110000
  3. 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

  1. (0b110111000001010000111100 &
  2. 0b111111110000000000000000) >> 16
  3. result 0b1101110

Hexadecimal number

each binary nibble can be in 1 of 16 stats

  1. Binary
  2. 0000
  3. 0001
  4. 0010
  5. 0011
  6. 0100
  7. 0101
  8. 0111
  9. 1000
  10. 1001
  11. 1010
  12. 1011
  13. 1100
  14. 1101
  15. 1110
  16. 1111

1101 1100 0001 0100 0011 1100
D C 1 4 3 C

Left Shift

extract middle byte of dc143c
1 byte = 8 bit

  1. (0xdc143c & (0xff << 8)) >> 8
  2. 0xdc143c 0b1101 1100 0001 0100 0011 1100
  3. 0xff << 8 0b 1111 1111 0000 0000
  4. result 0b 0001 0100 0000 0000
  5. >> 8
  6. result 0b 0001 0100
  7. 0x 1 4

Integer packed bits

cleaing bits with an inverse mask

  1. value 10101010 &
  2. mask 11110111
  3. result 10100010

image.png

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

  1. value 10101010 ^
  2. mask 01100111
  3. result 11000101
  1. bits = 0b1010
  2. mask = 0b0111
  3. bits ^= mask
  4. 0b1101

Bitwize Complement

  1. ~0b11110000
  2. 0b0000

计算 align

  1. // 对齐到ALIGNMENT, ALIGNMENT必须是2的n次方,也就是binary 0b100 0b1000 0b10000
  2. pub fn align_to_size(size: usize) -> usize {
  3. if size & (ALIGNMENT - 1) == 0 {
  4. return size;
  5. }
  6. size + (ALIGNMENT - (size & (ALIGNMENT - 1)))
  7. }
  8. 假如 ALIGNMENT = 8
  9. 8 = 1000
  10. ALIGNMENT - 1 = 7
  11. 7 = 0111
  12. // size & (ALIGNMENT - 1) == 0
  13. 这个说明,只要sizeALIGNMENT的倍数,这个等式成立
  14. 16 = 10000
  15. 24 = 11000
  16. 40 = 101000
  17. 否则会返回除ALIGNMENT的余数

set bit & clear bit

  1. a |= (1 << n) // set bit
  2. b &= ~(1<<n) // clear bit
  3. c ^= (1 << n) // toggle bit
  1. void binary(unsigned int n) {
  2. for (int i = 256; i > 0; i /= 2) {
  3. if (n & i) {
  4. printf(" 1");
  5. } else {
  6. printf(" 0");
  7. }
  8. }
  9. printf("\n");
  10. }

left/right most

  1. right = val & 0xff
  2. left = (val >> 8) & 0xff

get n bits from position p

  1. unsigned getbits(unsigned x, int p, int n) {
  2. return (x >> (p + 1 - n)) & ~(~0 << n);
  3. }

分析: 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位