C language rounds a number up to the power of 2 (a strange trick)

C language rounds a number up to the power of 2 (a strange trick)

uint32_t up_pow2(uint32_t n) {
    --n;
	for (int i = 0; i < 5; i++) {
		n |= n >> (1 << i);
	}
    return ++n;
}

or

uint32_t up_pow2(uint32_t n) {
    --n;
    n |= n >> 1;
    n |= n >> 2;
    n |= n >> 4;
    n |= n >> 8;
    n |= n >> 16;
    return ++n;
}

Comments

Popular posts from this blog

Python Receiving and parse JSON Data via UDP protocol

ubus lua client method and event registration code demo/example