How to round a number to a multiple of 8 in C

2 Answers

0 votes
#include <stdio.h>

// The next highest multiple of eight
unsigned int roundToMultipleOf(unsigned int number, unsigned int roundTo) {
    return (number + (roundTo - 1)) & ~(roundTo - 1);
}

int main() {
  printf("%d\n", roundToMultipleOf(9, 8));
  printf("%d\n", roundToMultipleOf(19, 8));
  printf("%d\n", roundToMultipleOf(71, 8));

  return 0;
}



/*
run:

16
24
72

*/

 



answered Jun 7, 2024 by avibootz
edited Jun 9, 2024 by avibootz
0 votes
#include <stdio.h>
#include <math.h>
 
unsigned int roundToMultipleOf(unsigned int number, unsigned int multipleOf) {
    return multipleOf * floor(number / multipleOf);
}
 
int main() {
  printf("%d\n", roundToMultipleOf(9, 8));
  printf("%d\n", roundToMultipleOf(19, 8));
  printf("%d\n", roundToMultipleOf(71, 8));
 
  return 0;
}
 
 
 
/*
run:
 
8
16
64
 
*/

 



answered Jun 8, 2024 by avibootz

Related questions

2 answers 101 views
2 answers 128 views
2 answers 137 views
2 answers 122 views
1 answer 130 views
2 answers 165 views
2 answers 119 views
...