PARP Research Group | Universidad de Murcia |
src/qvmath/qvbitcount.cppGo to the documentation of this file.00001 /* 00002 * Copyright (C) 2011, 2012. PARP Research Group. 00003 * <http://perception.inf.um.es> 00004 * University of Murcia, Spain. 00005 * 00006 * This file is part of the QVision library. 00007 * 00008 * QVision is free software: you can redistribute it and/or modify 00009 * it under the terms of the GNU Lesser General Public License as 00010 * published by the Free Software Foundation, version 3 of the License. 00011 * 00012 * QVision is distributed in the hope that it will be useful, 00013 * but WITHOUT ANY WARRANTY; without even the implied warranty of 00014 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 00015 * GNU Lesser General Public License for more details. 00016 * 00017 * You should have received a copy of the GNU Lesser General Public 00018 * License along with QVision. If not, see <http://www.gnu.org/licenses/>. 00019 */ 00020 00024 00025 #include <qvmath.h> 00026 00027 int qvIteratedBitCount(unsigned int n) 00028 { 00029 // Source for the code: http://gurmeet.net/puzzles/fast-bit-counting-routines/ 00030 int count = 0; 00031 while (n) 00032 { 00033 count += n & 0x1u; 00034 n >>= 1; 00035 } 00036 return count; 00037 } 00038 00039 int qvMITHAKMEMBitCount(unsigned int n) 00040 { 00041 // Source for the code: http://gurmeet.net/puzzles/fast-bit-counting-routines/ 00042 /* works for 32-bit numbers only */ 00043 /* fix last line for 64-bit numbers */ 00044 register unsigned int tmp; 00045 tmp = n - ((n >> 1) & 0xdb6db6db) - ((n >> 2) & 0x49249249); 00046 return ((tmp + (tmp >> 3)) & 0xc71c71c7) % 63; 00047 } 00048 00049 int qvNiftyParallelBitCount(unsigned int n) 00050 { 00051 // Source for the code: http://gurmeet.net/puzzles/fast-bit-counting-routines/ 00052 n = (n & 0x55555555) + ((n >> 1) & 0x55555555); 00053 n = (n & 0x33333333) + ((n >> 2) & 0x33333333); 00054 n = (n & 0x0f0f0f0f) + ((n >> 4) & 0x0f0f0f0f); 00055 return n % 255; 00056 } 00057 |