Where would we use shift operators (<<, >>)?

VitzzViperzz

Well-known member
Joined
Jan 16, 2017
Messages
75
Location
United Kingdom
Programming Experience
1-3
I just recently discovered C# has something called shift operators that shift the binary value of a number to the right or left. But where would this be useful?

The book I am readig just shows an example and not much explanation as to why they would be useful.

Thanks
 
One fairly common use is to store multiple smaller numeric values into one larger number. For instance, let's say that you wanted to store four bytes in an int:
int n = 0;
byte[] a = new byte[] {1, 2, 3, 4};

n = a[0];
n = (n << 8) | a[1];
n = (n << 8) | a[2];
n = (n << 8) | a[3];

The first 8 bits of the int are initially set using the 8 bits of the first byte. The int bits are all then shifted by 8 places and the first 8 bits set using the 8 bits of the second byte. All the bits are then shifted by 8 places twice more and the first 8 bits set again each time.
 
Back
Top Bottom