home *** CD-ROM | disk | FTP | other *** search
/ Tools / WinSN5.0Ver.iso / NETSCAP.50 / WIN1998.ZIP / ns / nsprpub / pr / src / misc / prlog2.c < prev    next >
Encoding:
C/C++ Source or Header  |  1998-04-08  |  1.6 KB  |  63 lines

  1. /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
  2. /*
  3.  * The contents of this file are subject to the Netscape Public License
  4.  * Version 1.0 (the "NPL"); you may not use this file except in
  5.  * compliance with the NPL.  You may obtain a copy of the NPL at
  6.  * http://www.mozilla.org/NPL/
  7.  * 
  8.  * Software distributed under the NPL is distributed on an "AS IS" basis,
  9.  * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
  10.  * for the specific language governing rights and limitations under the
  11.  * NPL.
  12.  * 
  13.  * The Initial Developer of this code under the NPL is Netscape
  14.  * Communications Corporation.  Portions created by Netscape are
  15.  * Copyright (C) 1998 Netscape Communications Corporation.  All Rights
  16.  * Reserved.
  17.  */
  18.  
  19. #include "prbit.h"
  20.  
  21. /*
  22. ** Compute the log of the least power of 2 greater than or equal to n
  23. */
  24. PR_IMPLEMENT(PRIntn) PR_CeilingLog2(PRUint32 n)
  25. {
  26.     PRIntn log2 = 0;
  27.  
  28.     if (n & (n-1))
  29.     log2++;
  30.     if (n >> 16)
  31.     log2 += 16, n >>= 16;
  32.     if (n >> 8)
  33.     log2 += 8, n >>= 8;
  34.     if (n >> 4)
  35.     log2 += 4, n >>= 4;
  36.     if (n >> 2)
  37.     log2 += 2, n >>= 2;
  38.     if (n >> 1)
  39.     log2++;
  40.     return log2;
  41. }
  42.  
  43. /*
  44. ** Compute the log of the greatest power of 2 less than or equal to n.
  45. ** This really just finds the highest set bit in the word.
  46. */
  47. PR_IMPLEMENT(PRIntn) PR_FloorLog2(PRUint32 n)
  48. {
  49.     PRIntn log2 = 0;
  50.  
  51.     if (n >> 16)
  52.     log2 += 16, n >>= 16;
  53.     if (n >> 8)
  54.     log2 += 8, n >>= 8;
  55.     if (n >> 4)
  56.     log2 += 4, n >>= 4;
  57.     if (n >> 2)
  58.     log2 += 2, n >>= 2;
  59.     if (n >> 1)
  60.     log2++;
  61.     return log2;
  62. }
  63.