Does x/2 compile to arithmetic right shift?

cmarcus

New member
If I write something like this:

c = (a/2) - (b/2);

where a,b,c are int16_t

will this compile to arithmetic right shifts? I need it to run faster than would be possible with division operations...
 
For signed integers: no, they are not the same.
Integer division is defined as rounding towards zero but a right-shift will round down (towards negative infinity). Right-shifting a negative value is usually undefined behaviour in C.
 
If you don't need to handle negative numbers, you'll probably get better performance by using uint32_t.

Intuitively you might expect 16 bits to be faster than 32, but on a 32 bit processor using 16 bits means the compiler often has to mask the upper 16 bits by inserting additional instructions. The actual math is always done with 32 bits, so by using only 16 you give the compiler more work to do.
 
If I write something like this:

c = (a/2) - (b/2);

where a,b,c are int16_t

will this compile to arithmetic right shifts? I need it to run faster than would be possible with division operations...
Then use explicit right shifts perhaps? The signed/unsigned issue is important too, and you may be able to save an instruction by doing the subtraction before the shift, although that is slightly different semantics.
 
Assuming a T_4.x's 1062 MCU the two divisions/(shifts on unsigned a&b) might 'dual execute' and then do a subtraction into c
 
Back
Top