本文共 1360 字,大约阅读时间需要 4 分钟。
When should you use bitwise operators?
Bitwise operators are used forsaving more space orsaving some time. There are also times when you need to use bitwise operators: if you're working with compression or some forms of encryption, or if you're working on low-level device control, error detection and correction algorithms, data compression, encryption algorithms, and optimization. Bit manipulation, in some cases,can obviate or reduce the need to loop over a data structure and can give many-fold speed ups, but the code can become rather more difficult to write and maintain. How many basic bitwise operations are there?
Source code that does bit manipulation usually makes use of the basic bitwise operations: AND, OR, XOR, NOT, and bit shifts. As a reminder, here are the truth tables : AND: 1 & 1 = 1, else are all 0 OR: 0 | 0 = 0, else are all 1 XOR: 1 ^ 0 = 0 ^ 1 = 1, else are 0 Left Shifts: 0001 << 1 = 0010, general bit_arg<<shift_arg equivalent to multiplication by 2^shift_arg Right Shifts: 0010 >> 1 = 0001, general bit_arg>>shift_arg equivalent to division by 2^shift_arg Some useful operations when coding.
Set negation: ALL_BITS_ONE ^ A Assign 2^bit to be 1: A |= 1<<bit Assign 2^bit to be 0: A &= ~(1<<bit) Check if 2^bit is 1: (A & 1<<bit) != 0 References:
转载地址:http://wexti.baihongyu.com/