{ans + = n << count”是什么意思?

时间:2019-09-20 03:29:43

标签: c bit-manipulation bitwise-operators bit-shift

// Function for multiplication 
int multiply(int n, int m) 
{   
    int ans = 0, count = 0; 
    while (m) 
    { 
        if (m % 2 == 1)               
            ans += n << count; 

        // increment of place value (count) 
        count++; 
        m /= 2; 
    } 
    return ans; 
} 

该表达是什么意思?如何以更适合初学者的形式重写此表达式?

2 个答案:

答案 0 :(得分:3)

表达式ans += n << count;的含义与以下内容相同:

int n_shifted = n << count;  /* bitshift n to the left by count bits */
ans = ans + n_shifted;       /* add n_shifted to ans */

答案 1 :(得分:1)

n左移count,然后将其添加到ans

n << 1  =   n * 2
n << 2  =   n * 4
n << 3  =   n * 8
n << 4  =   n * 16