Take the 2-minute tour ×

Multiplication and division can be achieved using bit operators, for example

i*2 = i<<1
i*3 = (i<<1) + i;
i*10 = (i<<3) + (i<<1)

and so on.

Is it actually faster to use say (i<<3)+(i<<1) to multiply with 10 than using i*10 directly? Is there any sort of input that can't be multiplied or divided in this way?

share|improve this question
Actually, cheap division by a constant other than a power of two is possible, but a tricky subjet to which you are not doing justice with "/Division … /divided" in your question. See for instance hackersdelight.org/divcMore.pdf (or get the book "Hacker's delight" if you can). –  Pascal Cuoq Jun 15 '11 at 11:35
It sound like something that could easily be tested. –  juanchopanza Jun 15 '11 at 11:51
As usual - it depends. Once upon a time I tried this in assembler on an Intel 8088 (IBM PC/XT) where a multiplication took a bazillion clocks. Shifts and adds executed a lot faster, so it seemed like a good idea. However, while multiplying the bus unit was free to fill the instruction queue and the next instruction could then start immediately. After a series of shifts and adds the instruction queue would be empty and the CPU would have to wait for the next instruction to be fetched from memory (one byte at a time!). Measure, measure, measure! –  Bo Persson Jun 15 '11 at 12:21
Also, beware that right-shifting is only well-defined for unsigned integers. If you have a signed integer, it's not defined whether 0 or the highest bit are padded from the left. (And don't forget the time it takes for someone else (even yourself) to read the code a year later!) –  Kerrek SB Jun 15 '11 at 12:56
Actually, a good optimizing compiler will implement multiplication and division with shifts when they are faster. –  Peter G. Jun 15 '11 at 14:44
show 6 more comments

14 Answers

up vote 265 down vote accepted

Short answer: Not likely.

Long answer: Your compiler has an optimizer in it that knows how to multiply as quickly as your target processor architecture is capable. Your best bet is to tell the compiler your intent clearly (i.e. i*2 rather than i << 1) and let it decide what the fastest assembly/machine code sequence is. It's even possible that the processor itself has implemented the multiply instruction as a sequence of shifts & adds in microcode.

Bottom line--don't spend a lot of time worrying about this. If you mean to shift, shift. If you mean to multiply, multiply. Do what is semantically clearest--your coworkers will thank you later. Or, more likely, curse you later if you do otherwise.

share|improve this answer
+1 for "your coworkers will thank you later." –  Michael Kristofik Jun 15 '11 at 12:31
Yep, as said the possible gains for almost every application will totally outweigh the obscurity introduced. Don't worry about this kind of optimisation prematurely. Build what is sematically clear, identify bottlenecks and optimise from there... –  Dave Jun 15 '11 at 15:20
Agreed, optimizing for readability and maintainability will probably net you more time to spend actually optimizing things that the profiler says are hot code paths. –  doug65536 Jan 2 '13 at 21:04
add comment

Just a concrete point of measure: many years back, I benchmarked two versions of my hashing algorithm:

hash( char const* s )
    unsigned h = 0;
    while ( *s != '\0' ) {
        h = 127 * h + (unsigned char)*s;
        ++ s;
    return h;


hash( char const* s )
    unsigned h = 0;
    while ( *s != '\0' ) {
        h = (h << 7) - h + (unsigned char)*s;
        ++ s;
    return h;

On every machine I benchmarked it on, the first was at least as fast as the second. Somewhat surprisingly, it was sometimes faster (e.g. on a Sun Sparc). When the hardware didn't support fast multiplication (and most didn't back then), the compiler would convert the multiplication into the appropriate combinations of shifts and add/sub. And because it knew the final goal, it could sometimes do so in less instructions than when you explicitly wrote the shifts and the add/subs.

Note that this was something like 15 years ago. Hopefully, compilers have only gotten better since then, so you can pretty much count on the compiler doing the right thing, probably better than you could. (Also, the reason the code looks so C'ish is because it was over 15 years ago. I'd obviously use std::string and iterators today.)

share|improve this answer
You may be interested in the following blog post, in which the author notes that modern optimizing compilers seem to reverse-engineer common patterns that programmers might use thinking them more efficient into their mathematical forms so as to really generate the most efficient instruction sequence for them. shape-of-code.coding-guidelines.com/2009/06/30/… –  Pascal Cuoq May 8 '12 at 17:19
@PascalCuoq Nothing really new about this. I discovered pretty much the same thing for Sun CC close to 20 years ago. –  James Kanze May 8 '12 at 17:56
add comment

This depends on the processor and the compiler. Some compilers already optimize code this way, others don't. So you need to check each time your code needs to be optimized this way.

Unless you desperately need to optimize, I would not scramble my source code just to save an assembly instruction or processor cycle.

share|improve this answer
Just to add a rough estimation: On a typical 16-Bit processor (80C166) adding two ints comes at 1-2 cycles, a multiplication at 10 cycles and a division at 20 cycles. Plus some move-operations if you optimize i*10 into multiple ops (each mov another +1 cycle). The most common compilers (Keil/Tasking) do not optimize unless for multiplications/divisions by a power of 2. –  Jens Jun 15 '11 at 11:40
And in general, the compiler optimizes code better than you do. –  Raging Scallion Jun 15 '11 at 11:41
I agree that when multiplying "quantities", the multiplication operator is generally better, but when dividing signed values by powers of 2, the >> operator is faster than / and, if the signed values can be negative, it's often semantically superior as well. If one needs the value which x>>4 would produce, that's a lot clearer than x < 0 ? -((-1-x)/16)-1 : x/16;, and I can't imagine how a compiler could optimize that latter expression to something nice. –  supercat Nov 20 '13 at 0:39
add comment

In addition to all the other good answers here, let me point out another reason to not use shift when you mean divide or multiply. I have never once seen someone introduce a bug by forgetting the relative precedence of multiplication and addition. I have seen bugs introduced when maintenance programmers forgot that "multiplying" via a shift is logically a multiplication but not syntactically of the same precedence as multiplication. x * 2 + z and x << 1 + z are very different!

If you're working on numbers then use arithmetic operators like + - * / %. If you're working on arrays of bits, use bit twiddling operators like & ^ | >> . Don't mix them; an expression that has both bit twiddling and arithmetic is a bug waiting to happen.

share|improve this answer
Avoidable with simple parenthesis? –  Joel B Jun 15 '11 at 14:59
@Joel: Sure. If you remember that you need them. My point is that it is easy to forget that you do. People who get in the mental habit of reading "x<<1" as though it were "x*2" get in the mental habit of thinking that << is the same precedence as multiplication, which it is not. –  Eric Lippert Jun 15 '11 at 15:49
Well, I find expression "(hi << 8) + lo" more intent-revealing than "hi*256 + lo". Probably it is a matter of taste, but sometimes it is more clear to write bit-twiddling. In most cases though I totally agree with your point. –  Ivan Danilov Jun 16 '11 at 1:56
@Ivan: And "(hi << 8) | lo" is even more clear. Setting the low bits of a bit array is not addition of integers. It is setting bits, so write the code that sets bits. –  Eric Lippert Jun 16 '11 at 6:59
Wow. Didn't think of it this way before. Thanks. –  Ivan Danilov Jun 16 '11 at 7:06
show 5 more comments

Shifting is generally a lot faster than multiplying at an instruction level but you may well be wasting your time doing premature optimisations. The compiler may well perform these optimisations at compiletime. Doing it yourself will affect readability and possibly have no effect on performance. It's probably only worth it to do things like this if you have profiled and found this to be a bottleneck.

Actually the division trick, known as 'magic division' can actually yield huge payoffs. Again you should profile first to see if it's needed. But if you do use it there are useful programs around to help you figure out what instructions are needed for the same division semantics. Here is an example : http://www.masm32.com/board/index.php?topic=12421.0

An example which I have lifted from the OP's thread on MASM32:

include ConstDiv.inc
mov eax,9999999
; divide eax by 100000
cdiv 100000
; edx = quotient

Would generate:

mov eax,9999999
mov edx,0A7C5AC47h
add eax,1
.if !CARRY?
    mul edx
shr edx,16
share|improve this answer
Link seems to be a random forum thread about liking math. –  Drew Hall Jun 15 '11 at 11:44
Crap. Posted wrong one. Corrected. –  Mike Kwan Jun 15 '11 at 11:44
@Drew for some reason your comment made me laugh and spill my coffee. thanks. –  asawyer Jun 15 '11 at 14:28
There are no random forum threads about liking math. Anyone who likes math knows how hard it is to generate a true "random" forum thread. –  Joel B Jun 15 '11 at 14:48
+1 for that thread about liking math is EPIC! –  Elijah Saounkine Jun 15 '11 at 19:23
show 1 more comment

Just tried on my machine compiling this :

int a = ...;
int b = a * 10;

When disassembling it produces output :

LEA EAX,DWORD PTR DS:[EAX+EAX*4] ; Multiply by 5 without shift !
SHL EAX, 1 ; Multiply by 2 using shift

This version is faster than your hand-optimized code with pure shifting and addition.

You really never know what the compiler is going to come up with, so it's better to simply write a normal multiplication and let him optimize the way he wants to, except in very precise cases where you know the compiler cannot optimize.

share|improve this answer
You would have gotten a big upvote for this if you had skipped the part about the vector. If the compiler can fix the multiply it can also see that the vector doesn't change. –  Bo Persson Jun 15 '11 at 16:01
How can a compiler know a vector size won't change without making some really dangerous assumptions? Or have you never heard of concurrency... –  Charles Goodwin Jun 15 '11 at 17:46
Ok, so you loop over a global vector with no locks? And I loop over a local vector who's address hasn't been taken, and call only const member functions. At least my compiler realizes that the vector size will not change. (and soon someone will probably flag us for chatting :-). –  Bo Persson Jun 15 '11 at 19:06
@BoPersson Finally, after all this time, I removed my statement about the compiler not being able to optimize away vector<T>::size(). My compiler was quite ancient! :) –  Raging Scallion Dec 5 '12 at 19:28
add comment


It might or might not be on your machine - if you care, measure in your real-world usage.

A case study - from 486 to core i7

Benchmarking is very difficult to do meaningfully, but we can look at a few facts. From http://www.penguin.cz/~literakl/intel/s.html#SAL and http://www.penguin.cz/~literakl/intel/i.html#IMUL we get an idea of x86 clock cycles needed for arithmetic shift and multiplication. Say we stick to "486" (the newest one listed), 32 bit registers and immediates, IMUL takes 13-42 cycles and IDIV 44. Each SAL takes 2, and adding 1, so even with a few of those together shifting superficially looks like a winner.

These days, with the core i7:

(from http://software.intel.com/en-us/forums/showthread.php?t=61481)

The latency is 1 cycle for an integer addition and 3 cycles for an integer multiplication. You can find the latencies and thoughput in Appendix C of the "Intel® 64 and IA-32 Architectures Optimization Reference Manual", which is located on http://www.intel.com/products/processor/manuals/.

(from some Intel blurb)

Using SSE, the Core i7 can issue simultaneous add and multiply instructions, resulting in a peak rate of 8 floating-point operations (FLOP) per clock cycle

That gives you an idea of how far things have come. The optimisation trivia - like bit shifting versus * - that was been taken seriously even into the 90s is just obsolete now. Bit-shifting is still faster, but for non-power-of-two mul/div by the time you do all your shifts and add the results it's slower again. Then, more instructions means more cache faults, more potential issues in pipelining, more use of temporary registers may mean more saving and restoring of register content from the stack... it quickly gets too complicated to quantify all the impacts definitively but they're predominantly negative.

functionality in source code vs implementation

More generally, your question is tagged C and C++. As 3rd generation languages, they're specifically designed to hide the details of the underlying CPU instruction set. To satisfy their language Standards, they must support multiplication and shifting operations (and many others) even if the underlying hardware doesn't. In such cases, they must synthesize the required result using many other instructions. Similarly, they must provide software support for floating point operations if the CPU lacks it and there's no FPU. Modern CPUs all support * and <<, so this might seem absurdly theoretical and historical, but the significance thing is that the freedom to choose implementation goes both ways: even if the CPU has an instruction that implements the operation requested in the source code in the general case, the compiler's free to choose something else that it prefers because it's better for the specific case the compiler's faced with.

Examples (with a hypothetical assembly language)

source           literal approach         optimised approach
#define N 0
int x;           .word x                xor registerA, registerA
x *= N;          move x -> registerA
                 move x -> registerB
                 A = B * immediate(0)
                 store registerA -> x
  ...............do something more with x...............

Instructions like exclusive or (xor) have no relationship to the source code, but xor-ing anything with itself clears all the bits, so it can be used to set something to 0. Source code that implies memory addresses may not entail any being used.

These kind of hacks have been used for as long as computers have been around. In the early days of 3GLs, to secure developer uptake the compiler output had to satisfy the existing hardcore hand-optimising assembly-language dev. community that the produced code wasn't slower, more verbose or otherwise worse. Compilers quickly adopted lots of great optimisations - they became a better centralised store of it than any individual assembly language programmer could possibly be, though there's always the chance that they miss a specific optimisation that happens to be crucial in a specific case - humans can sometimes nut it out and grope for something better while compilers just do as they've been told until someone feeds that experience back into them.

So, even if shifting and adding is still faster on some particular hardware, then the compiler writer's likely to have worked out exactly when it's both safe and beneficial.


If your hardware changes you can recompile and it'll look at the target CPU and make another best choice, whereas you're unlikely to ever want to revisit your "optimisations" or list which compilation environments should use multiplication and which should shift. Think of all the non-power-of-two bit-shifted "optimisations" written 10+ years ago that are now slowing down the code they're in as it runs on modern processors...!

Thankfully, good compilers like GCC can typically replace a series of bitshifts and arithmetic with a direct multiplication when any optimisation is enabled (i.e. ...main(...) { return (argc << 4) + (argc << 2) + argc; } -> imull $21, 8(%ebp), %eax) so a recompilation may help even without fixing the code, but that's not guaranteed.

Strange bitshifting code implementing multiplication or division is far less expressive of what you were conceptually trying to achieve, so other developers will be confused by that, and a confused programmer's more likely to introduce bugs or remove something essential in an effort to restore seeming sanity. If you only do non-obvious things when they're really tangibly beneficial, and then document them well (but don't document other stuff that's intuitive anyway), everyone will be happier.

General solutions versus partial solutions

If you have some extra knowledge, such as that your int will really only be storing values x, y and z, then you may be able to work out some instructions that work for those values and get you your result more quickly than when the compiler's doesn't have that insight and needs an implementation that works for all int values. For example, consider your question:

Multiplication and division can be achieved using bit operators...

You illustrate multiplication, but how about division?

int x;
x >> 1;   // divide by 2?

According to the C++ Standard 5.8:

-3- The value of E1 >> E2 is E1 right-shifted E2 bit positions. If E1 has an unsigned type or if E1 has a signed type and a nonnegative value, the value of the result is the integral part of the quotient of E1 divided by the quantity 2 raised to the power E2. If E1 has a signed type and a negative value, the resulting value is implementation-defined.

So, your bit shift has an implementation defined result when x is negative: it may not work the same way on different machines. But, / works far more predictably. (It may not be perfectly consistent either, as different machines may have different representations of negative numbers, and hence different ranges even when there are the same number of bits making up the representation.)

You may say "I don't care... that int is storing the age of the employee, it can never be negative". If you have that kind of special insight, then yes - your >> safe optimisation might be passed over by the compiler unless you explicitly do it in your code. But, it's risky and rarely useful as much of the time you won't have this kind of insight, and other programmers working on the same code won't know that you've bet the house on some unusual expectations of the data you'll be handling... what seems a totally safe change to them might backfire because of your "optimisation".


Yes... as mentioned above, negative numbers have implementation defined behaviour when "divided" by bit-shifting.

share|improve this answer
Very nice answer. Core i7 vs. 486 comparison is enlightening! –  Drew Hall Jun 24 '11 at 20:07
add comment

Shift and integer multiply instructions have similar performance on most modern CPUs - integer multiply instructions were relatively slow back in the 1980s but in general this is no longer true. Integer multiply instructions may have higher latency, so there may still be cases where a shift is preferable. Ditto for cases where you can keep more execution units busy (although this can cut both ways).

Integer division is still relatively slow though, so using a shift instead of division by a power of 2 is still a win, and most compilers will implement this as an optimisation. Note however that for this optimisation to be valid the dividend needs to be either unsigned or must be known to be positive. For a negative dividend the shift and divide are not equivalent!

#include <stdio.h>

int main(void)
    int i;

    for (i = 5; i >= -5; --i)
        printf("%d / 2 = %d, %d >> 1 = %d\n", i, i / 2, i, i >> 1);
    return 0;


5 / 2 = 2, 5 >> 1 = 2
4 / 2 = 2, 4 >> 1 = 2
3 / 2 = 1, 3 >> 1 = 1
2 / 2 = 1, 2 >> 1 = 1
1 / 2 = 0, 1 >> 1 = 0
0 / 2 = 0, 0 >> 1 = 0
-1 / 2 = 0, -1 >> 1 = -1
-2 / 2 = -1, -2 >> 1 = -1
-3 / 2 = -1, -3 >> 1 = -2
-4 / 2 = -2, -4 >> 1 = -2
-5 / 2 = -2, -5 >> 1 = -3

So if you want to help the compiler then make sure the variable or expression in the dividend is explicitly unsigned.

share|improve this answer
Integer multiplies are microcoded for example on PlayStation 3's PPU, and stall the whole pipeline. It's recommended to avoid integer multiplies on some platforms still :) –  Maister Jun 20 '11 at 14:21
Many unsigned divisions are - assuming the compiler knows how - implemented using unsigned multiplies. One or two multiplies @ a few clock cycles each can do the same work as a division @ 40 cycles each and up. –  Olof Forshell Mar 29 '12 at 10:54
@Olof: true, but only valid for division by a compile-time constant of course –  Paul R Mar 29 '12 at 10:58
add comment

It completely depends on target device, language, purpose, etc.

Pixel crunching in a video card driver? Very likely, yes!

.NET business application for your department? Absolutely no reason to even look into it.

For a high performance game for a mobile device it might be worth looking into, but only after easier optimizations have been performed.

share|improve this answer
add comment

As far as I know in some machines multiplication can need upto 16 to 32 machine cycle. So Yes, depending on the machine type, bitshift operators are faster than multiplication / division.

However certain machine do have their math processor, which contains special instructions for multiplication/division.

share|improve this answer
The people writing compilers for those machines have also likely read the Hackers Delight and optimize accordingly. –  Bo Persson Jun 15 '11 at 12:10
add comment

Don't do unless you absolutely need to and your code intent requires shifting rather than multiplication/division.

In typical day - you could potentialy save few machine cycles (or loose, since compiler knows better what to optimize), but the cost doesn't worth it - you spend time on minor details rather than actual job, maintaining the code becomes harder and your co-workers will curse you.

You might need to do it for high-load computations, where each saved cycle means minutes of runtime. But, you should optimize one place at a time and do performance tests each time to see if you really made it faster or broke compilers logic.

share|improve this answer
add comment

Python test performing same multiplication 100 million times against the same random numbers.

>>> from timeit import timeit
>>> setup_str = 'import scipy; from scipy import random; scipy.random.seed(0)'
>>> N = 10*1000*1000
>>> timeit('x=random.randint(65536);', setup=setup_str, number=N)
1.894096851348877 # Time from generating the random #s and no opperati

>>> timeit('x=random.randint(65536); x*2', setup=setup_str, number=N)
>>> timeit('x=random.randint(65536); x << 1', setup=setup_str, number=N)

>>> timeit('x=random.randint(65536); x*10', setup=setup_str, number=N)
>>> timeit('x=random.randint(65536); (x << 3) + (x<<1)', setup=setup_str, number=N)

>>> timeit('x=random.randint(65536); x // 2', setup=setup_str, number=N)
>>> timeit('x=random.randint(65536); x / 2', setup=setup_str, number=N)
>>> timeit('x=random.randint(65536); x >> 1', setup=setup_str, number=N)

So in doing a shift rather than multiplication/division by a power of two in python, there's a slight improvement (~10% for division; ~1% for multiplication). If its a non-power of two, there's likely a considerable slowdown.

Again these #s will change depending on your processor, your compiler (or interpreter -- did in python for simplicity).

As with everyone else, don't prematurely optimize. Write very readable code, profile if its not fast enough, and then try to optimize the slow parts. Remember, your compiler is much better at optimization than you are.

share|improve this answer
add comment

I agree with the marked answer by Drew Hall. The answer could use some additional notes though.

For the vast majority of software developers the processor and compiler are no longer relevant to the question. Most of us are far beyond the 8088 and MS-DOS. It is perhaps only relevant for those who are still developing for embedded processors...

At my software company Math (add/sub/mul/div) should be used for all mathematics. While Shift should be used when converting between data types eg. ushort to byte as n>>8 and not n/256.

share|improve this answer
I agree with you, too. I follow the same guideline subconsciously, though I haven't ever had a formal requirement to do so. –  Drew Hall Jan 24 at 9:15
add comment

In the case of signed integers and right shift vs division, it can make a difference. For negative numbers, the shift rounds rounds towards negative infinity whereas division rounds towards zero. Of course the compiler will change the division to something cheaper, but it will usually change it to something that has the same rounding behavior as division, because it is either unable to prove that the variable won't be negative or it simply doesn't care. So if you can prove that a number won't be negative or if you don't care which way it will round, you can do that optimization in a way that is more likely to make a difference.

share|improve this answer
or cast the number to unsigned –  Lie Ryan Jun 15 '11 at 18:12
Are you sure that the shifting behaviour is standardized? I was under the impression that right-shift on negative ints is implementation-defined. –  Kerrek SB Jun 16 '11 at 1:43
While you should perhaps mention that code which relies upon any particular behavior for right-shifting negative numbers should document that requirement, the advantage to right-shifting is huge in cases where it naturally yields the right value and the division operator would generate code to waste time computing an unwanted value which user code would then have to waste additional time adjusting to yield what the shift would have given in the first place. Actually, if I had my druthers, compilers would have an option to squawk at attempts to perform signed division, since... –  supercat Nov 1 '13 at 18:17
...code which knows the operands are positive could improve optimization if it cast to unsigned before division (possibly casting back to signed afterward), and code which knows that operands might be negative should generally deal with that case explicitly anyhow (in which case one may as well assume them to be positive). –  supercat Nov 1 '13 at 18:18
add comment

Your Answer


