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

2 Answers

0 votes
#include <iostream>

// The next highest multiple of eight
unsigned int roundToMultipleOf(unsigned int number, unsigned int roundTo) {
    return (number + (roundTo - 1)) & ~(roundTo - 1);
}
 
int main() {
  std::cout << roundToMultipleOf(9, 8) << "\n";
  std::cout << roundToMultipleOf(19, 8) << "\n";
  std::cout << roundToMultipleOf(71, 8) << "\n";
}
 
 
 
/*
run:
 
16
24
72
 
*/

 



answered Jun 7, 2024 by avibootz
edited Jun 9, 2024 by avibootz
0 votes
#include <iostream>
#include <cmath>
 
unsigned int roundToMultipleOf(unsigned int number, unsigned int multipleOf) {
    return multipleOf * floor(number / multipleOf);
}
  
int main() {
  std::cout << roundToMultipleOf(9, 8) << "\n";
  std::cout << roundToMultipleOf(19, 8) << "\n";
  std::cout << roundToMultipleOf(71, 8) << "\n";
}
  
  
  
/*
run:
  
8
16
64
  
*/

 



answered Jun 8, 2024 by avibootz

Related questions

2 answers 118 views
2 answers 128 views
2 answers 137 views
2 answers 122 views
1 answer 130 views
2 answers 165 views
2 answers 118 views
...