Question

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?

Was it helpful?

Solution

As per your comments, you want -32768 mapped to 0, and 32767 mapped to 255. Thus, the formula you want is:

short s = /* input value */;
unsigned char c = (unsigned char) ((s + 32768) / 256);

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:

unsigned char c = (unsigned char) ((s + 32768) >> 8);

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 -mthumb and GCC 4.7.2):

    mov     r3, #128
    lsl     r3, r3, #8
    add     r0, r0, r3
    lsr     r0, r0, #8
    uxtb    r0, r0

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.

OTHER TIPS

just cast a pointer.

unsigned char *bytes = (unsigned char*)&yourvalue;

now, bytes[0] will hold hold one byte of your value, and bytes[1] will hold th other. the order depends on the endianness of your system

You could use union this way:

#include <stdio.h>

union Word {
    struct {
        unsigned char high;
        unsigned char low;
    } byte;
    unsigned short word;
};

int main(int argc, char **argv) {

    union Word word;
    word.word = 0x1122;

    printf("L = 0x%x, H = 0x%x", word.byte.low, word.byte.high);

    return 0;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top