I've implemented a color palette scrolling routine for my C project, which looks like so:
void scrollPalette(u16 arr[])
{
if (g_scrollDir)
{
u16 first = arr[0];
for (u8 i = 0; i < 15; i++)
{
arr[i] = arr[i + 1];
}
arr[15] = first;
}
else
{
u16 last = arr[15];
for (u8 i = 15; i > 0; i--)
{
arr[i] = arr[i - 1];
}
arr[0] = last;
}
}
Where g_scrollDir determines the direction, once a scroll has reached it's end at either index 0(when decrementing) or index 15(when incrementing).
This works just fine, But I'm curious if there's any neater or more compact way of doing this in C? Any suggestions?
What you're doing is totally fine, but here's how I might do it:
struct palette {
u16 items[16];
u8 first_i;
};
void scrollPalette(struct palette *p, bool scroll_dir)
{
if (scroll_dir) {
p->first_i = (p->first_i + 1) % 16;
} else {
p->first_i = p->first_i == 0 ? 15 : p->first_i - 1;
}
}
Then you need to access and display the palette differently, for example:
u16 paletteGet(struct palette *p, u8 n) {
return p->items[(p->first_i + n) % 16];
}