Compute buffer size at compile-time



Hello,

Consider:

#define BUFFER_SIZE 1234 /* or some other value */
uint8_t buffer[BUFFER_SIZE];
int do_stuff(uint8_t *buf);

where do_stuff() does something with each octet in the buffer.

Assume I've come up with do_stuff_2() similar to do_stuff() but
that works with 16 octets at a time.

I need to compute N at compile time
such that N >= 1234 && N % 16 == 0

I came up with: (BS stands for BUFFER_SIZE)

(BS & ~15) + ((BS&15 != 0) << 4)

which can be written in a simpler way:

((BS-1) & ~15) + 16

Although there might be a problem if BS is an int and 0.
I think 0-1 is well-defined if BS is an unsigned int?

I welcome your comments.

I also toyed with the idea of returning the next power of 2:

31 -> 32
32 -> 32
33 -> 64
48 -> 64
64 -> 64
65 -> 128

but I couldn't figure out how to compute it at compile-time elegantly.
(I need a loop which I could completely unroll... ugly.)

Regards.
.



Relevant Pages