Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ROUNDUP? what does it do? in C++

Tags:

c++

Can someone explain to me what this does?

#define ROUNDUP(n,width) (((n) + (width) - 1) & ~unsigned((width) - 1))
like image 976
SuperString Avatar asked May 16 '26 17:05

SuperString


1 Answers

Providing width is an even power of 2 (so 2,4,8,16,32 etc), it will return a number equal to or greater than n, which is a multiple of width, and which is the smallest value meeting that criteria.

So width = 16; 5->16, 7->16, 15->16, 16->16, 17->32, 18->32 etc.

EDIT I started out on providing an explanation of why this works as it does, as I sense that's really what the OP wants, but it turned into a rather convoluted story. If the OP is still confused, I'd suggest working through a few simple examples, say width = 16, n=15,16,17. Remember that & = bitwise AND, ~ = bitwise complement, and to use binary representation exclusively as you work through the examples.

like image 170
Bill Forster Avatar answered May 19 '26 05:05

Bill Forster



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!