I was doing some basic audio programming in C# using the NAudio package and I came across the following expression and I have no idea what it means, as i've never seen the << operator being used before. So what does << mean?
Please give a quick explaination of this expression.
short sample = (short)((buffer[index + 1] << 8) | buffer[index + 0]);
The << operator shifts the left-hand value left by the (right-hand value) bits. Your example does nothing! 1 shifted 0 bits to the left is still 1. However, 1 << 1 is 2, 1 << 2 is 4, etc.
The bitwise shift operators are the right-shift operator ( >> ), which moves the bits of an integer or enumeration type expression to the right, and the left-shift operator ( << ), which moves the bits to the left.
The "<<" is a shift left operator. x << y shifts bit pattern x y position left. For example, if x was 0001 0101 and y was 1 then the result would be 0010 1010. It's like someone's pushed each bit left one. Copy link CC BY-SA 2.5.
a<<b for integers means "shift left". The bitwise representation of a is shifted left b bits. This is the same as multiplying by (2 to the power of b ).
The left-shift operator (<<) shifts its first operand left by the number of bits specified by its second operand. The type of the second operand must be an int. << Operator (MSDN C# Reference)
For binary numbers it is a bitwise operation that shifts all of the bits of its operand; every bit in the operand is simply moved a given number of bit positions, and the vacant bit-positions are filled in.
Arithmetic shifts can be useful as efficient ways of performing multiplication or division of signed integers by powers of two. Shifting left by n bits on a signed or unsigned binary number has the effect of multiplying it by 2n. Shifting right by n bits on a two's complement signed binary number has the effect of dividing it by 2n, but it always rounds down (towards negative infinity). This is different from the way rounding is usually done in signed integer division (which rounds towards 0). This discrepancy has led to bugs in more than one compiler.
An other usage is work with color bits. Charles Petzold Foundations article "Bitmaps And Pixel Bits" shows an example of << when working with colors:
ushort pixel = (ushort)(green << 5 | blue);
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