Search code examples
cbit-shift

Invert operation for bitwise in C


Dear all C programmer:

X = 1 << N; (left shift)

how to recover N from X ?

Thanks


Solution

  • In a while loop, keep shifting right until X==1, record how many times you have to shift right and the counter will give you N.

    int var = X;
    int count = 0;
    while (var != 1){
        var >>= 1; 
        count++;
    }
    printf("N is %d", count);