math.c 964 B

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. // Unsigned Division and Modulo without / and %
  2. word MATH_divmodU(word dividend, word divisor, word mod)
  3. {
  4. word quotient = 0;
  5. word remainder = 0;
  6. if(divisor == 0)
  7. return 0;
  8. word i;
  9. for(i = 31 ; i >= 0 ; i--)
  10. {
  11. quotient = quotient << 1;
  12. remainder = remainder << 1;
  13. remainder = remainder | ((dividend & (1 << i)) >> i);
  14. if((unsigned int) remainder >= (unsigned int) divisor)
  15. {
  16. remainder = remainder - divisor;
  17. quotient = quotient | 1;
  18. }
  19. if (i == 0)
  20. if (mod == 1)
  21. return remainder;
  22. else
  23. return quotient;
  24. }
  25. return 0;
  26. }
  27. // Unsigned positive integer division
  28. word MATH_divU(word dividend, word divisor)
  29. {
  30. return MATH_divmodU(dividend, divisor, 0);
  31. }
  32. // Unsigned positive integer modulo
  33. word MATH_modU(word dividend, word divisor)
  34. {
  35. return MATH_divmodU(dividend, divisor, 1);
  36. }