Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why bit shifting?

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?

like image 923
Jeremy Holovacs Avatar asked Sep 22 '11 18:09

Jeremy Holovacs


People also ask

Is bit shifting Good for encryption?

One simple and good way to encrypt data is through rotation of bits or sometimes called bit shifting.

Is bit shifting faster than dividing?

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.

Is bit shifting faster than adding?

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.

What is the difference between bit shifting and bit rotating?

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.


1 Answers

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;
like image 175
Justin Niessner Avatar answered Sep 23 '22 05:09

Justin Niessner