Merge pull request #1071 from ReneSac/devel

Zero is not a power of two. Fixes #1047
This commit is contained in:
Andreas Rumpf 2014-04-06 20:12:46 +02:00
commit b988f75a35
2 changed files with 14 additions and 12 deletions

View file

@ -376,7 +376,7 @@ static inline void GCGuard (void *ptr) { asm volatile ("" :: "X" (ptr)); }
# define GC_GUARD # define GC_GUARD
#endif #endif
/* Test to see if nimrod and the C compiler agrees on the size of a pointer. /* Test to see if nimrod and the C compiler agree on the size of a pointer.
On disagreement, your C compiler will say something like: On disagreement, your C compiler will say something like:
"error: 'assert_numbits' declared as an array with a negative size" */ "error: 'assert_numbits' declared as an array with a negative size" */
typedef int assert_numbits[sizeof(NI) == sizeof(void*) && NIM_INTBITS == sizeof(NI)*8 ? 1 : -1]; typedef int assert_numbits[sizeof(NI) == sizeof(void*) && NIM_INTBITS == sizeof(NI)*8 ? 1 : -1];

View file

@ -75,28 +75,30 @@ proc binom*(n, k: int): int {.noSideEffect.} =
result = (result * (n + 1 - i)) div i result = (result * (n + 1 - i)) div i
proc fac*(n: int): int {.noSideEffect.} = proc fac*(n: int): int {.noSideEffect.} =
## computes the faculty function ## computes the faculty/factorial function.
result = 1 result = 1
for i in countup(2, n): for i in countup(2, n):
result = result * i result = result * i
proc isPowerOfTwo*(x: int): bool {.noSideEffect.} = proc isPowerOfTwo*(x: int): bool {.noSideEffect.} =
## returns true, if x is a power of two, false otherwise. ## returns true, if `x` is a power of two, false otherwise.
## Negative numbers are not a power of two. ## Zero and negative numbers are not a power of two.
return (x and -x) == x return (x != 0) and ((x and (x - 1)) == 0)
proc nextPowerOfTwo*(x: int): int = proc nextPowerOfTwo*(x: int): int {.noSideEffect.} =
## returns the nearest power of two, so that ## returns `x` rounded up to the nearest power of two.
## result**2 >= x > (result-1)**2. ## Zero and negative numbers get rounded up to 1.
result = x - 1 result = x - 1
when defined(cpu64): when defined(cpu64):
result = result or (result shr 32) result = result or (result shr 32)
result = result or (result shr 16) when sizeof(int) > 16:
result = result or (result shr 8) result = result or (result shr 16)
when sizeof(int) > 8:
result = result or (result shr 8)
result = result or (result shr 4) result = result or (result shr 4)
result = result or (result shr 2) result = result or (result shr 2)
result = result or (result shr 1) result = result or (result shr 1)
inc(result) result += 1 + ord(x<=0)
proc countBits32*(n: int32): int {.noSideEffect.} = proc countBits32*(n: int32): int {.noSideEffect.} =
## counts the set bits in `n`. ## counts the set bits in `n`.