What do two left-angle brackets “<<” mean in C#?

前端 未结 15 2003
长情又很酷
长情又很酷 2020-12-12 13:55

Basically the questions in the title. I\'m looking at the MVC 2 source code:

[Flags]
public enum HttpVerbs {
    Get = 1 << 0,
    Post = 1 << 1,         


        
15条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-12 14:09

    It is Bitwise shift left it works by shifting digits of binary equivalent of number by the given (right hand side) numbers.

    so:

    temp = 14 << 2
    

    binary equivalent of 14 is 00001110 shifting it 2 times means pushing zero from right hand side and shifting each digit to left side which make it 00111000 equals to 56.

    visual

    In your example:

    i < (1 << list.Count)
    
    • 0000000001 = 1 if list.Count = 0 result is 0000000001 = 1
    • 0000000001 = 1 if list.Count = 1 result is 0000000010 = 2
    • 0000000001 = 1 if list.Count = 2 result is 0000000100 = 4
    • 0000000001 = 1 if list.Count = 3 result is 0000001000 = 8

    and so on. In general it is equal 2 ^ list.Count (2 raised to the power of list.Count)

提交回复
热议问题