If size is a int variable
int size = 10;
And I want to round up size to a multiple of 8, what is the difference between the two ways:
A:
size = 1 + ((size - 1)/8);
size = size * 8;
B:
size = (size/8+1)*8;
Thanks in advance.
If size is a int variable
int size = 10;
And I want to round up size to a multiple of 8, what is the difference between the two ways:
A:
size = 1 + ((size - 1)/8);
size = size * 8;
B:
size = (size/8+1)*8;
Thanks in advance.
Is there any difference between [these] two ways to round a number to a multiple of 8 in C[?]
Yes. They produce different results for inputs that are already multiples of 8. Approach (A) returns such inputs unchanged, but approach (B) returns the next larger multiple of 8 (supposing no overflow).
The two are doing different things:
Here is the sequence of outputs for both snippets for values 0..19, with differences highlighted:
Method A keeps multiples of 8 the same value and rounds other values up.
Method B won't work for multiples of 8, as it rounds those up as well.
For example: (16/8+1)*8 == (2+1)*8 == 3*8 == 24
.
As others has stated, the A and B behave differently. Just try with size = 8
for both. Solution B is for sure wrong as 8
results in 16
.
Rounding can be done in several ways. Especially negative numbers can be tricky. Should -4
result in -8
or 0
?
I would go for round to nearste
with Round half away from zero
like this:
size = (size >= 0) ? 8*((size+4)/8) : 8*((size-4)/8);
See https://en.wikipedia.org/wiki/Rounding for more about rounding.
Rounding up to a power of 2 can be done like
size = (size + 7) & (~7)
Sometimes helps when you're on a CPU that has no fast multiplication / division
Different results when size
is 8, 16, 24, 32 ...
Different results when size
is -7, -15, -23 ...
.
A
is correct for values greater than 1.
B
is not correct for positive multiples of 8.
Both fail for size == 0
. Unclear if size < 0
is important for OP.
To do unsigned
rounding up to a multiple of N
which also works for size == 0
.
#define N 8
unsigned size;
unsigned rounded_size = (size + N - 1) % N;