Multiply with negative integer just by shifting.
Posted
by stex
on Stack Overflow
See other posts from Stack Overflow
or by stex
Published on 2010-05-01T21:21:59Z
Indexed on
2010/05/01
21:27 UTC
Read the original article
Hit count: 132
c
Hi,
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?
© Stack Overflow or respective owner