Basic knowledge and properties of bit operations (concise summary)

Table of contents

Introduction

basic knowledge

Common properties


Introduction

The numbers in the computer are stored in the memory in the form ofbinary. Using bit operations is to directly store the integers in the memory. The binary bits are operated, so its execution efficiency is very high. Try to use bit operations in the program to operate, which will greatly improve the performance of the program.

basic knowledge

  • AND operation (&): The result is 1 when the corresponding bits of both numbers are 1.
  • Or operation (|): The result is 1 when one of the corresponding bits of the two numbers is 1.
  • XOR operation (^): The result is 1 when the corresponding bits of the two numbers are different.
  • NOT operation (~): negate each bit of a number.
  • Left shift (<<): binary representation of shifting a number of bits to the left. Each left shift is equivalent to multiplying the number by 2.
  • Right shift (>>): Binary representation of right shift by a number of bits. Each right shift by one bit is equivalent to dividing the number by 2.

Common properties

  • Any number ANDed with 0 is 0
  • Any number ORed with 0 is itself
  • Double NOT operation can make decimals quickly rounded
  • Any number XORed with itself is 0, so any number XORed with 0 is itself
x^x=0,x^0=x
(比较两值是否相等)
  • Implement multiplication and division
数 a 向右移一位,相当于将 a 除以 2;数 a 向左移一位,相当于将 a 乘以 2
  • XOR completes variable value exchange
//位与操作
void swap(int &a, int &b) {
  a ^= b;
  b ^= a;
  a ^= b;
}
  • ANDing with 1 can be used to determine the parity of a number
只要根据数的最后一位是 0 还是 1 来决定即可,为 0 就是偶数,为 1 就是奇数
  • (a |= 1 << i) : Set the i + 1th binary bit to 1
  • [ a &= ~(1 << i) ] : Set the i + 1th binary bit to 0

Guess you like

Origin blog.csdn.net/qq_62799214/article/details/133886506