What does the operator “<<” mean in C#?

前端 未结 9 1120
无人共我
无人共我 2020-12-05 22:57

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

9条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-05 23:33

    The bitwise operator has already been explained quite a few times already. Let's say that buffer[0] contains 1, buffer[1] contains 2 and index is 0 and replace these values:

    short sample = (short)((buffer[1] << 8) | buffer[0]);
    short sample = (short)((1 << 8) | 2);
    

    Now, a semi-graphical representation. This is the numeral 1 in a binary representation:

    0000 0001
    

    Shifting eight positions to the left would make this number to "overflow" from a single byte. However, the compiler is smart enough to give us more room.

    0000 0001 0000 0000
    

    Now, the right part: the number 2 looks like this in binary:

    0000 0010
    

    And the "|" operator (bitwise OR) makes just put the two values together and comparing bit per bit.

      0000 0001 0000 0000
    | 0000 0000 0000 0010
    = 0000 0001 0000 0010
    

    And the final value is stored in your "sample" variable (in this case, 258.) The reverse operation is similar:

    buffer[0] = sample & 255;
    buffer[1] = (sample & (255 << 8)) >> 8;
    

提交回复
热议问题