Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiply with negative integer just by shifting

Tags:

c

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?

like image 480
stex Avatar asked May 01 '10 21:05

stex


People also ask

How do you use bit shifting for negative integers?

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.

Can shift operator be applied to negative numbers?

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.

How do you multiply a negative integer?

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.

Does shifting left multiply?

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.


1 Answers

Get the compiler to do it, then check the produced assembly.

like image 102
Puppy Avatar answered Sep 30 '22 04:09

Puppy