Skip to content

Instantly share code, notes, and snippets.

@sarnesjo
Created April 29, 2011 23:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sarnesjo/949232 to your computer and use it in GitHub Desktop.
Save sarnesjo/949232 to your computer and use it in GitHub Desktop.
Branch-free triangle wave generator functions
#include <stdio.h>
#include <stdlib.h>
// assumes abs is branch-free
// see http://graphics.stanford.edu/~seander/bithacks.html#IntegerAbs
int triangle_wave_gen0(int i, int max_value) // min_value fixed to 0
{
i += max_value;
i %= max_value * 2;
i -= max_value;
i = abs(i);
return i;
}
int triangle_wave_gen(int i, int min_value, int max_value)
{
return triangle_wave_gen0(i, max_value - min_value) + min_value;
}
int main()
{
for(int i = 0; i < 12; ++i)
printf("#%d: %d\n", i, triangle_wave_gen(i, 10, 15));
for(int i = 0; i < 12; ++i)
printf("#%d: %d\n", i, triangle_wave_gen0(i, 5));
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment