Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

multiplying an integer by 5 using bitwise operator

I am trying to multiply an integer by 5 using bitwise operations. But there seems to be a bug in my code that I can't identify. Here's my code

#include <stdio.h>

#define print_integer(exp) printf("%s : %d\n", #exp, (exp))

int multiply(int num) {
    int ans;
    ans = num << 2 + num;
    return ans;
}

int main() {
    int a = 1, b = 2, c = 3;
    print_integer(multiply(a));
    print_integer(multiply(b));
    print_integer(multiply(c));
    return 0;
}

Edit:- The bug is in line ans = num << 2 + num;

like image 512
Sanjay-sopho Avatar asked Mar 20 '26 12:03

Sanjay-sopho


1 Answers

The precedence between << and + is counter intuitive. Use parentheses and compile with -Wall to get useful warnings abut this kind of potential mistake:

#include <stdio.h>

#define print_integer(exp) printf("%s : %d\n", #exp, (exp))

int multiply(int num) {
      return (num << 2) + num;
}

int main(void) {
    int a = 1, b = 2, c = 3;
    print_integer(multiply(a));
    print_integer(multiply(b));
    print_integer(multiply(c));
    return 0;
}
like image 51
chqrlie Avatar answered Mar 23 '26 01:03

chqrlie



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!