Search code examples
c++cpuunsigned

Does unsigned math require more CPU instructions?


Take an C++ integral variable i, and suppose that you're multiplying its value by 2.

If i has signedness, I believe that the operation is somewhat equivalent, at least mathematically, to:

i = i << 1;

But if i's type is unsigned, then since unsigned values do not overflow but are performed modulo their range, presumably the operation is something like this:

i = (i << 1) & (decltype(i))-1;

Now, I figure that the actual machine instructions will probably be more concise than a sequence of shifts for multiplication. But would a modern, say x86, CPU have a specific instruction for unsigned/modulo math? Or will performing math with unsigned values tend to cost an additional instruction, when compared to math with signed values?

(Yes, it would be ridiculous to care about this whilst programming; I'm interested out of pure curiosity.)


Solution

  • No, it doesn't take more instructions, at least on x86.

    For some operations (e.g. addition and subtraction), the same instruction is used for both signed and unsigned types. This is possible since they work the same when using 2's complement representation of signed values.

    There is also no difference for left-shift: The leftmost bit is simply discarded by the hardware, and there is no need to perform a bitwise-and like in your example.

    For other operations (e.g. right-shift), there are separate instructions: SHR (shift right) for unsigned values and SAR (shift arithmetic right) for signed values, which preserves the sign bit.

    There are also separate instructions for signed/unsigned multiplication and division: MUL/IMUL and DIV/IDIV, where IMUL and IDIV are used for signed values.