From: "Suraj N. Kurapati" Date: 2006-08-08T06:26:24+09:00 Subject: Re: nextPowerOf2(n) -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Ch Skilbeck wrote: > Can someone tell me if there's a better way to do this? It takes a > number and returns the next power of 2 up (or the original if it was > already a power of 2) > > def nextPowerOf2(n) > raise "integer please" if !n.kind_of? Integer > high = 0 > count = 0 > (0..n.size * 8 - 2).each {|b| count += n[b] ; high = b if n[b] != 0} > 1 << high + (count > 1 ? 1 : 0) > end def nextPowerOf2(n); n.to_s(2).length; end -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.2.2 (GNU/Linux) iD8DBQFE16/fmV9O7RYnKMcRAoCQAKCyUMDF8qVWCH4Vtu+CnV2UOBJTJgCghnIp zS+Li0sTuB6E1O0lStXPn+Q= =4y44 -----END PGP SIGNATURE-----