Reputation: 21
I need to multiply an int by a fraction using bitwise operators without loops and such.
For example, I need to multiply by x by 3/8.
I thought you would:
int value = (x << 1) + x; // Multiply by 3
value = (value >> 3); // Divide by 8
But that doesnt work. I tried googling binary times fraction but that give floating point examples. I dont know exactly if this homework is for floating point but my hunch is no but getting me prepared for it. So any suggestions?
I need to round toward zero so any suggestions? This doesnt work for the number -268435457.
Upvotes: 2
Views: 4775
Reputation: 533432
To avoid an overflow you can cast to (long long) and back to (int) for the final result. To cause the >> 3
to round toward zero you need to add 7 (8-1) for a negative number. There are a few ways of doing this. Using these approaches gives you -100663296.
Upvotes: 0
Reputation: 26251
You probably want
int value = (x << 1) + x;
value = (value >> 3);
note that:
(x << 1) + 1 = 2*x + 1; // ignoring issues about overflow
To adjust for negative values, you can explicitly check for sign:
int value = (x << 1) + x;
value = value >> 3;
value = value + ((x >> 31) & 1); // for 32 bit; for 64 bit you have to use x >> 63
Upvotes: 4
Reputation: 636
Did you try:
int value = (x << 1) + x; // Multiply by 3
value = (value >> 3); // Divide by 8
i.e. in your second statement replace 'x' with 'value'. Also, value will loose the decimal points.
Upvotes: 1