I’m working on a Cortex M0 cpu, which doesn’t have hardware division, so every time I divide something, the GCC libary function is used. Now one of the division I do the most is dividing by 256, to convert shorts into bytes. Is there some way I can do this more efficiently (for example by bit-shifting) than the default GCC library will do it?
Share
As per your comments, you want -32768 mapped to 0, and 32767 mapped to 255. Thus, the formula you want is:
The other commenters have noted that you can do that divide-by-256 with a right-shift or various other tactics, which is true — a reasonable version of this would be:
However, there is no need for such optimizations. GCC is very smart about converting divide-by-constant operations into special-case implementations, and in this case it compiles both of these into exactly the same code (tested with
-O2 -mcpu=cortex-m0 -mthumband GCC 4.7.2):If you try to be too clever (as with the union or pointer-cast examples in other answers), you are likely to just confuse it and get something worse — especially since those work by memory loads, and adding 32768 means you already have the value in a register.