[Solved] C confused about bitwise shift operation


This is less to do with C, and more to do with mathematics.

The hash << 5 + hash expression is the same as hash * 32 + hash or just hash * 33.

Basic algebra states these things are true (these are written in C):

/* #1 */ (a * b + a * c) == (a * (b + c))
/* #2 */ (a) == (a * 1)

Applying #2, we can say:

(hash * 32 + hash) == (hash * 32 + hash * 1)

Now applying #1, we can find:

(hash * 32 + hash * 1) == (hash * (32 + 1))

This can be reduced to:

hash * 33

This is basic mathematics, but maybe you are tired or overworked and just can’t see how this works 🙂

3

solved C confused about bitwise shift operation