# Thread: Bitwise Operator Help

1. ## Bitwise Operator Help

Hello, I am writing a program that does Multiplication using Bitwise Operation. I can get the following code to compile but keep on getting 229344 for an answer. Also if I just run the "times" function as a stand alone app. , I will get correct output except when I have to negative numbers to compute. Any suggestions on what I might be doing wrong ? Thank you .

Code:
```#include <stdlib.h>
#include <stdio.h>
#include <ctype.h>

int times (int a, int b)
{
int result;
result=0;
while(b != 0)               // Iterate the loop till b==0
{
if (b&01)               // Logical ANDing of the value of b with 01
result=result+a;   // Update the result with the new value of a.
a<<=1;                // Left shifting the value contained in 'a' by 1.
b>>=1;               // Right shifting the value contained in 'b' by 1.
}
return result;
}

const int TEXT_SIZE = 100;

int main ()
{
printf("Hello, I'm a program that multplies integers. \n");

do {
int a;
int b;

char text[TEXT_SIZE];

printf("Please enter the first integer or 'Q' to quit:  ");
fgets(text,TEXT_SIZE,stdin);

if  ( toupper(text[0])== 'Q')
break;

a = atoi(text);

printf ("Please enter the second intger or 'Q' to quit:  ");
fgets(text,TEXT_SIZE,stdin);

if  ( toupper(text[0])== 'Q')
break;

b = atoi(text);

printf("The product for %d and %d is %d.\n\n", a,b,times(a,b));

}
while (1);
return(EXIT_SUCCESS);
getch();

}```

2. Signed ints use the most significant bit to indicate polarity, so the shift will change that.

3. Program appears to work fine for positive integers... I never get 229344 so I don't know where that comes from. Like the previous poster said, negative numbers pose a special case... Best to turn the numbers positive before doing the calculations... and then negate the result if warranted.

Popular pages Recent additions