3

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;

Codor
  • 17,447
  • 9
  • 29
  • 56
Sanjay-sopho
  • 429
  • 3
  • 15
  • 5
    `ans = (num<<2) + num;` https://en.wikipedia.org/wiki/Operators_in_C_and_C%2B%2B#Operator_precedence – wildplasser Dec 04 '16 at 15:14
  • ... cause `+` has precedence over `<<`. look at https://msdn.microsoft.com/en-us/library/aa691323(v=vs.71).aspx – Charles Bretana Dec 04 '16 at 15:17
  • Oh thanks, that worked. – Sanjay-sopho Dec 04 '16 at 15:19
  • 2
    Do you consider `+` to be a _bitwise operator_? I would not think so. Yet if `+` is a _bitwise operator_, then `*` is certainly one too and code simplifies to `int multiply(int num) { return num*5; }`. – chux - Reinstate Monica Dec 04 '16 at 15:22
  • Possible duplicate of [Multiplication of two integers using bitwise operators](http://stackoverflow.com/questions/4456442/multiplication-of-two-integers-using-bitwise-operators) – phuclv Dec 04 '16 at 15:46

2 Answers2

3

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;
}
chqrlie
  • 131,814
  • 10
  • 121
  • 189
-1

You are adding the num after the change ( num<<2 ) , set a temp value for num .

int tmp = num ; 
ans = num << 2 + tmp ;