Bit manipulation

来源:互联网 发布:c语言英语单词 编辑:程序博客网 时间:2024/04/30 11:18

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 optimizationBit manipulation, in some cases,can obviate or reduce the need to loop over a data structure and can give many-fold speed upsbut 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 
NOT: !0 = 1, !0 = 1
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 union: A | B
Set intersection: A & B
Set subtration: A & ~B
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://en.wikipedia.org/wiki/Bit_manipulation
http://www.cprogramming.com/tutorial/bitwise_operators.html
http://www.geeksforgeeks.org/fundamentals-of-algorithms/