Am Mon, 18 May 2015 22:16:47 -0700 schrieb Andrei Alexandrescu <seewebsiteforem...@erdani.org>:
> But that has branches in it. So I came up with: > > bool isPowerOf2(uint x) > { > return (x & (x - 1) | !x) == 0; > } > > which has no branches at least with dmd, see http://goo.gl/TVkCwc. > > Any ideas for faster code? > > > Thanks, > > Andrei Any faster ?! This is already minimal assembly code with pretty looks! While you are at it, you might also need "round pointer up to" and "round pointer down to", which can be implemented with bit ops for power-of-2 multiples. Its the kind of stuff that's not really a std.algorithm candidate, but still somewhat common in memory management code. Often these and other little helpers end up in everyones stdlib_extensions.d which I suppose don't look all that different. Who has some of these in their code?: - isPowerOf2, nextLargerPowerOf2 - roundUp/Down to multiple of X - increment with wraparound at X - clamp value (low, high or both ends) - check if numerical value is in between two others - compile time "iota" - format an argument as it would appear in source code (i.e. add quotes around strings) -- Marco