Reputation:
I was recently looking at a config file that was saving some cryptic values. I happened to have the source available, so I took a look at what it was doing, and it was saving a bunch of different values and bit shifting them into each other. It mystified me why someone would do that. My question, then, is: is there an obvious advantage to storing numeric data in this way? I can see how it might make for a slightly smaller value to store, byte-wise, but it seems like a lot of work to save a couple of bytes of storage. It also seems like it would be significantly slower.
The other possibility that occurred to me is that is was used for obfuscation purposes. is this a common usage of bit shifting?
Upvotes: 12
Views: 4113
Reputation: 369
Sometimes (especially in older Windows programming), there will be information encoded in "high order" and "low order" bits of a value... and it's sometimes necessary to shift to get the information out. I'm not 100% sure on the reasons behind that, aside from it might make it convenient to return a 64-bit value with two 32-bit values encoded in it (so you can handle it with a single return value from a method call).
I agree with your assertions about needless complexity though, I don't see a lot of applications outside of really heavy number-crunching/cryptography stuff where this would be necessary.
Upvotes: 1
Reputation: 245429
This is one of the common usages of bit shifting. There are several benefit:
1) Bit-shift operations are fast.
2) You can store multiple flags in a single value.
If you have an app that has several features, but you only want certain (configurable) ones enabled, you could do something like:
[Flags]
public enum Features
{
Profile = 1,
Messaging = 1 << 1,
Signing = 1 << 2,
Advanced = 1 << 3
}
And your single value to enable Messaging and Advanced would be:
(1 << 1) + (1 << 3) = 2 + 16 = 18
<add name="EnabledFeatures" value="18" />
And then to figure out if a given feature is enabled, you just perform some simple bitwise math:
var AdvancedEnabled =
EnabledFeatures & Features.Advanced == Features.Advanced;
Upvotes: 11
Reputation: 86505
Bit shifting seems more common in systems-level languages like C, C++ and assembly, but I've seen it here and there in C# too. It's not often used so much to save space, though, as it is for one (or both) of two typical reasons:
Anyone who uses it in a high-level language solely to save space or obfuscate their code is almost always prematurely optimizing (and/or is an idiot). The space savings rarely justify the added complexity, and bit shifts really aren't complex enough to stop someone determined to understand your code.
Upvotes: 5
Reputation: 19956
I have a project that stores day/hour matrix of available hours during one week. So it has 24x7 values that have to be stored somehow.
I chose to store it as 7 ints, so each day is represented with one integer, and each hour in it as one bit. Just an example where it can be useful.
Upvotes: 4