From: "Kroeger, Simon (ext)" Date: 2006-08-07T23:48:52+09:00 Subject: Re: nextPowerOf2(n) > From: Ch Skilbeck > Sent: Monday, August 07, 2006 4:30 PM > > Hi, > > 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) Specifically, are there features of Ruby that I > should be using in this case? > > Cheers, > Charlie. > > 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) 2 ** (Math.log(n) / Math.log(2)).ceil end cheers Simon