codepad
[
create a new paste
]
login
|
about
Language:
C
C++
D
Haskell
Lua
OCaml
PHP
Perl
Plain Text
Python
Ruby
Scheme
Tcl
/* Find log base 2 */ /* Copied as it is from : http://graphics.stanford.edu/~seander/bithacks.html#IntegerLogObvious */ int m1(unsigned int v) { const bool isLittleEndian = true; int r; // result of log_2(v) goes here union { unsigned int u[2]; double d; } t; // temp t.u[isLittleEndian] = 0x43300000; t.u[!isLittleEndian] = v; t.d -= 4503599627370496.0; return (t.u[isLittleEndian] >> 20) - 0x3FF; } void check(unsigned int i) { const int m = m1(i); const unsigned int ans = 1 << m; printf("%08X -> %d\n", i, m); if (ans > i || (ans < 0x80000000U & (ans * 2 < i) ) ) cout << "*** Failed for " << i << endl; } int main() { srand(0); unsigned int tn = 0U; const unsigned int mod = 0x1000000; while(tn <= 0xFFFFFFFFU - mod) { check(tn); tn += (rand() & (mod - 1)); } for(int i = 0; i < 1; ++i) check( rand() & 0xF ); for(int i = 0; i < 10; ++i) check( rand() & 0xFF ); for(int i = 0; i < 100; ++i) check( rand() & 0xFFFF ); for(int i = 0; i < 1000; ++i) check( rand() & 0xFFFFF ); check(0xFFFFFFFFU); }
Private
[
?
]
Run code
Submit