0

I wish to use a block size that is padded to the nearest 32 so my function below I thought would be 36/32 = 1.125, ceil = 2, 2*32 = 64 however somewhere from converting from double to int I am getting the answer of 32.

double dbl;
int block_size;

dbl = ceil(36/32);
block_size = (int)dbl*32; // equals 32
Jason
  • 607
  • 3
  • 9
  • 25

6 Answers6

4

When you call ceil(36/32) you're dividing two integers, so you get an integer as a result (1 in this case). Try dividing doubles: ceil(36.0/32.0).

andreas-hofmann
  • 2,378
  • 11
  • 15
2

36/32 will perform integer division and will result in dbl being equal to 1. Try using (36.0 / 32.0). Also, try to avoid using magic numbers What is a magic number, and why is it bad?

Community
  • 1
  • 1
Mathieu Borderé
  • 4,357
  • 2
  • 16
  • 24
2

If you like to allign to 32 (= 2^5) do this:

int block_size;
...
block_size = block_size+31 & ~31;

First add 31 and then mask all bits except the first 5 bits.

(32 + 31) & ~31 = 32

(33 + 31) & ~31 = 64

Rabbid76
  • 202,892
  • 27
  • 131
  • 174
2

The values '36' and '32' in the line 'dbl = ceil(36/32);' are integers. This means the result of '36/32' 32 is 1, and 'ceil(1)' is 1.

Make them floating point values to get the correct answer:

dbl = ceil(36.0/32.0);
Evil Dog Pie
  • 2,300
  • 2
  • 23
  • 46
2

Try

#define ALIGNMENT 32

...

int input = 36;
int rounded_up = ((input + (ALIGNMENT - 1)) / ALIGNMENT) * ALIGNMENT;

Don't use floating point unless absolutely necessary. They cause more trouble and are likely slower than integers. The compiler will likely use masking for this pattern if it uses powers of two.

And avoid magic numbers in your code.

too honest for this site
  • 12,050
  • 4
  • 30
  • 52
2

All previous answers are correct, but they missed casting. If the values you have are integers, i.e you get the value to round from a function or an integer variable, you can use:

int MyRoundedValue = ceil((double)MyInputInteger/32.0);

Note the casting to double of your int variable and the divisor, 32.0, expressed as a double.
Anyway using the ceil() function is an heavy job for such simple problem, it is more simple to act on solutions that avoid the use of ceil and floats (as many of that above).

Frankie_C
  • 4,764
  • 1
  • 13
  • 30