Understand the shift operator

<< is the left-shift operator; this takes the binary representation of a value, and moves all the bits “n” places to the left (except for “mod”, see “1”), back-filling with zeros.

>> is the right-shift operator; this does nearly the opposite (moving to the right), except for signed values (i.e. those that can be negative) it back-fills with 1s for negative values, else zeros.

1:

The shift operator is essentially “mod” the width of the data. An int is 32 bits, so a left shift of 33 (in Int32) is exactly the same as a left shift of 1. You don’t get all zeros. A long is 64 bits, so a left-shift of 33 gives a different answer (original times 2^33).

2:

Each left shift (within the data width) is the same (for integers) as x2 – so <<4 is x2x2x2x2 = x16.

This is simple binary:

0000000001 = 1

<< goes to

0000000010 = 2

<< goes to

0000000100 = 4

<< goes to

0000001000 = 8

Leave a Comment