bitcount.h

Go to the documentation of this file.
00001 
00002 
00003 
00014 
00015 // Copyright (C) 1997-2010 by Pawel Pilarczyk.
00016 //
00017 // This file is part of the Homology Library.  This library is free software;
00018 // you can redistribute it and/or modify it under the terms of the GNU
00019 // General Public License as published by the Free Software Foundation;
00020 // either version 2 of the License, or (at your option) any later version.
00021 //
00022 // This library is distributed in the hope that it will be useful,
00023 // but WITHOUT ANY WARRANTY; without even the implied warranty of
00024 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
00025 // GNU General Public License for more details.
00026 //
00027 // You should have received a copy of the GNU General Public License along
00028 // with this software; see the file "license.txt".  If not, write to the
00029 // Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
00030 // MA 02111-1307, USA.
00031 
00032 // Started on November 29, 2005. Last revision: November 29, 2005.
00033 
00034 
00035 #ifndef _CHOMP_STRUCT_BITCOUNT_H_
00036 #define _CHOMP_STRUCT_BITCOUNT_H_
00037 
00038 namespace chomp {
00039 namespace homology {
00040 
00041 
00042 extern unsigned char bitcounttable [];
00043 
00044 inline int bitcountbyte (char n)
00045 {
00046         return bitcounttable [static_cast<unsigned char> (n)];
00047 } /* bitcountbyte */
00048 
00049 inline int bitcount (int number)
00050 {
00051         if (!number)
00052                 return 0;
00053         unsigned int n = static_cast<unsigned int> (number);
00054         if (n < 256)
00055                 return bitcountbyte (static_cast<unsigned char> (n));
00056         int c = 0;
00057         while (n > 255)
00058         {
00059                 if (n & 1)
00060                         ++ c;
00061                 n >>= 1;
00062         }
00063         return c + bitcountbyte (static_cast<unsigned char> (n));
00064 } /* bitcount */
00065 
00066 
00067 } // namespace homology
00068 } // namespace chomp
00069 
00070 #endif // _CHOMP_STRUCT_BITCOUNT_H_
00071 
00073