Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Could someone help explain what this C one liner does?

Tags:

c

I can usually figure out most C code but this one is over my head.

#define kroundup32(x) (--(x), (x)|=(x)>>1, (x)|=(x)>>2, (x)|=(x)>>4, (x)|=(x)>>8, (x)|=(x)>>16, ++(x))

an example usage would be something like:

int x = 57;
kroundup32(x);
//x is now 64

A few other examples are:

1 to 1
2 to 2
7 to 8
31 to 32
60 to 64
3000 to 4096

I know it's rounding an integer to it's nearest power of 2, but that's about as far as my knowledge goes.

Any explanations would be greatly appreciated.

Thanks

like image 749
GWW Avatar asked Aug 02 '10 03:08

GWW


People also ask

What is a one-liner explanation?

Definition of one-liner 1 : a very succinct joke or witticism. 2 : a succinct or meaningful and especially accurate statement.

What is single line comment in C?

Single-line comments start with two forward slashes ( // ). Any text between // and the end of the line is ignored by the compiler (will not be executed).


1 Answers

(--(x), (x)|=(x)>>1, (x)|=(x)>>2, (x)|=(x)>>4, (x)|=(x)>>8, (x)|=(x)>>16, ++(x))
  1. Decrease x by 1
  2. OR x with (x / 2).
  3. OR x with (x / 4).
  4. OR x with (x / 16).
  5. OR x with (x / 256).
  6. OR x with (x / 65536).
  7. Increase x by 1.

For a 32-bit unsigned integer, this should move a value up to the closest power of 2 that is equal or greater. The OR sections set all the lower bits below the highest bit, so it ends up as a power of 2 minus one, then you add one back to it. It looks like it's somewhat optimized and therefore not very readable; doing it by bitwise operations and bit shifting alone, and as a macro (so no function call overhead).

like image 174
thomasrutter Avatar answered Sep 23 '22 14:09

thomasrutter