问题
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.
回答1:
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
回答2:
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.
回答3:
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.
来源:https://stackoverflow.com/questions/7356927/how-to-multiply-an-int-with-a-fraction