0

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.

zyz
  • 83
  • 1
  • 3
  • 10

6 Answers6

3

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).

John Bollinger
  • 160,171
  • 8
  • 81
  • 157
2

The two are doing different things:

  • The first sequence correctly keeps multiples of 8 in place
  • The second sequence rounds 8 up to 16, 16 up to 24, and so on.

Here is the sequence of outputs for both snippets for values 0..19, with differences highlighted:

  • 0 8 8
  • 1 8 8
  • 2 8 8
  • 3 8 8
  • 4 8 8
  • 5 8 8
  • 6 8 8
  • 7 8 8
  • 8 8 16
  • 9 16 16
  • 10 16 16
  • 11 16 16
  • 12 16 16
  • 13 16 16
  • 14 16 16
  • 15 16 16
  • 16 16 24
  • 17 24 24
  • 18 24 24
  • 19 24 24
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
2

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.

dbush
  • 205,898
  • 23
  • 218
  • 273
1

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.

Support Ukraine
  • 42,271
  • 4
  • 38
  • 63
1

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

tofro
  • 5,640
  • 14
  • 31
1

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;
chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256