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?
One simple and good way to encrypt data is through rotation of bits or sometimes called bit shifting.
Shifting bits left and right is apparently faster than multiplication and division operations on most, maybe even all, CPUs if you happen to be using a power of 2. However, it can reduce the clarity of code for some readers and some algorithms.
Bit-shifting is still faster, but for non-power-of-two mul/div by the time you do all your shifts and add the results it's slower again.
Bit rotation is similar to bit shift. It actually is bit shift but with a difference. The end bits, MSB or LSB are not any more lost and they come back on the other side of the string. Bit rotation is also known as circular bit shift.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With