Lets say we have a negative integer say int a;
is there a faster implementation of -a?
Do I have to do some bitwise operation on this?
There's almost certainly nothing faster than the machine code NEG instruction that your compiler will most likely turn this into.
If there was, I'm sure the compiler would use it.
For a twos-complement number, you could NOT it and add 1 but that's almost certainly going to be slower. But I'm not entirely certain that the C/C++ standards mandate the use of twos-complement (they may, I haven't checked).
I think this question belongs with those that attempt to rewrite strcpy() et al to get more speed. Those people naively assume that the C library strcpy() isn't already heavily optimized by using special machine code instructions (rather than a simplistic loop that would be most people's first attempt).
Have you run performance tests which seem to indicate that your negations are taking an overly long time?
<subtle-humor-or-what-my-wife-calls-unfunny>
</subtle-humor-or-what-my-wife-calls-unfunny>
To clarify Pax's statement,
C++ compilers are not mandated to use two's complement, except in 1 case. When you convert a signed type to an unsigned type, if the number is negative, the result of the conversion must be the 2's complement representation of the integer.
In short, there is not a faster way than -a; even if there were, it would not be portable. Keep in mind as well that premature optimization is evil. Profile your code first and then work on the bottlenecks.
See The C++ Programming Language, 3rd Ed., section C.6.2.1.
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