Sunday 26 August 2012

Refer to http://www.cprogramming.com/tutorial/bitwise_operators.html

It is a good article addressing what the bitwise is in c/c++ programming language.

Basically, BitWise can be used as multiplication and division with factor of corresponding power of 2 depending on leftshift or rightshift, and logical operation such as AND, OR, XOR, ~.

When should you use bitwise operators?

Bitwise operators are good for saving space -- but many times, space is hardly an issue. And one problem with working at the level of the individual bits is that if you decide you need more space or want to save some time -- for instance, if we needed to store information about 9 cars instead of 8 -- then you might have to redesign large portions of your program. On the other hand, sometimes you can use bitwise operators to cleverly remove dependencies, such as by using ~0 to find the largest possible integer. And bit shifting to multiply by two is a fairly common operation, so it doesn't affect readability in the way that advanced use of bit manipulation can in some cases (for instance, using XOR to switch the values stored in two variables). 

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 a system that expects bit fields to be used to store boolean attributes.

Summary

You should now be familiar with six bitwise operators: 

Works on bits for left argument, takes an integer as a second argument
bit_arg<<shift_arg
Shifts bits to of bit_arg shift_arg places to the left -- equivalent to multiplication by 2^shift_arg
bit_arg>>shift_arg
Shifts bits to of bit_arg shift_arg places to the right -- equivalent to integer division by 2^shift_arg 

Works on the bits of both arguments
left_arg & right_arg
Takes the bitwise AND of left_arg and right_arg
left_arg ^ right_arg
Takes the bitwise XOR of left_arg and right_arg
left_arg | right_arg
Works on the bits of only argument
~arg
Reverses the bits of arg 

Skills and knowledge You also know a couple of neat tricks that you can use when performance is critical, or space is slow, or you just need to isolate and manipulate individual bits of a number.


No comments:

Post a Comment