首页 > 解决方案 > “ans += n << count”是什么意思?

问题描述

// 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; 
} 

那个表达是什么意思?如何以对初学者更友好的形式重写这个表达式?

标签: cbit-manipulationbitwise-operatorsbit-shift

解决方案


该表达式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 */

推荐阅读