I'm trying to find a way to multiply an integer value with negative value just with bit shifting.
Usually I do this by shifting with the power of 2 which is closest to my factor and just adding / subtracting the rest, e.g. x * 7 = ((x << 3) - x)
Let's say I'd want to calculate x * -112
. The only way I can imagine is -((x << 7) - (x << 4)
, so to calculate x * 112
and negate it afterwards.
Is there a "prettier" way to do this?
For signed numbers, the sign bit is used to fill the vacated bit positions. In other words, if the number is positive, 0 is used, and if the number is negative, 1 is used. The result of a right-shift of a signed negative number is implementation-dependent.
The left shift and right shift operators should not be used for negative numbers. The result of is undefined behaviour if any of the operands is a negative number.
When you multiply a negative number by a positive number then the product is always negative. When you multiply two negative numbers or two positive numbers then the product is always positive. 3 times 4 equals 12. Since there is one positive and one negative number, the product is negative 12.
Description. Shifts bits to the left. The number to the left of the operator is shifted the number of places specified by the number to the right. Each shift to the left doubles the number, therefore each left shift multiplies the original number by 2.
Get the compiler to do it, then check the produced assembly.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With