When do I need to use bitshift/unary operators etc? [duplicate]
Possible Duplicates:
Have you ever had to use bit shifting in real projects? When to use Shift operators << >> in C# ?
Although I should have learnt this a long time ago, what coding tasks/scenarios are useful for bitshifts/unary operators and the like?
I never see a need for these in the coding I do (mostly LOB apps), so what sort of tasks/problems would make me come to开发者_如何学运维 the conclusion I need to use these concepts?
Thanks
This doesn't work that way, you don't just "need" to use them. It's more that you need to make a given task that happens to be faster if you use a bitshift operation.
Usually there are very few things you "need" them to, but they're useful for performance on a lot of mathematical functions as well as to improve hash functions and other cryptographic operations (which are in fact math based...). Basically, in the majority of the cases, to improve performance of a given algorithm.
Anything that involves some sort of bit-level encoding, for example UTF-8 and other multi-byte character encodings. In these cases you need to check individual bits and combine bit strings together.
Also the simplest case is when you want to store various flags in a single byte. You might define something like:
const uint FOO_DELETED = 0x01;
const uint FOO_DRAFT = 0x02;
const uint FOO_WHATEVER = 0x04;
// ...
Then you can combine these together in a single byte:
byte my_flags = FOO_DELETED | FOO_WHATEVER;
And extract them:
bool is_deleted = (my_flags & FOO_DELETED);
Not a ton of use in day-to-day stuff when you live in C#. It's mostly when interoperating with unmanaged code that has sub-byte granularity (struct marshaling, etc), dealing with byte-order conversion (little-endian/big-endian). Under the covers, enums with FlagsAttribute already does it.
Lots of unmanaged stuff uses bitfields for very efficient storage. Bitfields can be a royal pain in C#. I've done some managed user-mode driver framework coding, and some work with the raw TIFF file format in C#, and it sucked. C/C++ have better facilities for dealing with them.
Another example is to multiply or to divide by 2.
int a = 10;
int result = 0;
result = a << 1; // result is 10 * 2 == 20;
result = a >> 1; // result is 10 / 2 == 5;
These operations are usually much faster than the "real" operator * or /
精彩评论