From owner-freebsd-hackers Sat Aug 21 10:13:35 1999 Delivered-To: freebsd-hackers@freebsd.org Received: from numeri.campus.luth.se (numeri.campus.luth.se [130.240.197.103]) by hub.freebsd.org (Postfix) with ESMTP id 589A015160 for ; Sat, 21 Aug 1999 10:13:32 -0700 (PDT) (envelope-from k@numeri.campus.luth.se) Received: from numeri.campus.luth.se (localhost [127.0.0.1]) by numeri.campus.luth.se (8.9.3/8.9.3) with ESMTP id TAA76885; Sat, 21 Aug 1999 19:11:35 +0200 (CEST) (envelope-from k@numeri.campus.luth.se) Message-Id: <199908211711.TAA76885@numeri.campus.luth.se> X-Mailer: exmh version 2.0.2 2/24/98 To: Nick Hibma Cc: FreeBSD Hackers mailing list Subject: Re: from number to power of two In-reply-to: Your message of "Sat, 21 Aug 1999 12:54:32 +0200." Mime-Version: 1.0 Content-Type: text/plain; charset=us-ascii Date: Sat, 21 Aug 1999 19:11:35 +0200 From: Johan Karlsson Sender: owner-freebsd-hackers@FreeBSD.ORG Precedence: bulk X-Loop: FreeBSD.ORG At Sat, 21 Aug 1999 12:54:32 +0200, Nick Hibma wrote: > >Does anyone know an inexpensive algorithm (O(1)) to go from an number to >the next (lower or higher) power of two. > >1 -> 1 >2,3 -> 2 >4,5,6,7 -> 4 >8,9,10,11,12,13,14,15 -> 8 >etc. > >So %1101 should become either %10000 or %1000. > >The only solution I have so far is a table. That is a possibility as the >the highest number will be 32 I think. This small prog works at least on x86 ===== #include #include int main(int argc, char **argv){ int i, j, k; sscanf(argv[1], "%d", &i); j = 1<<(fls(i)-1); k = 1<<(fls(i-1)); printf("%d %d %d\n", j, i, k); return 0; } ===== /Johan K To Unsubscribe: send mail to majordomo@FreeBSD.org with "unsubscribe freebsd-hackers" in the body of the message