判断一个整数中有多少bit为1

Counting bits set (naive way)

unsigned int v; // count the number of bits set in v
unsigned int c; // c accumulates the total bits set in v

for (c = 0; v; v >>= 1)
{
  c += v & 1;
}

The naive approach requires one iteration per bit, until no more bits are set. So on a 32-bit word with only the high set, it will go through 32 iterations.

Counting bits set by lookup table

static const unsigned char BitsSetTable256[256] = 
{
#   define B2(n) n,     n+1,     n+1,     n+2
#   define B4(n) B2(n), B2(n+1), B2(n+1), B2(n+2)
#   define B6(n) B4(n), B4(n+1), B4(n+1), B4(n+2)
    B6(0), B6(1), B6(1), B6(2)
};

unsigned int v; // count the number of bits set in 32-bit value v
unsigned int c; // c is the total bits set in v

// Option 1:
c = BitsSetTable256[v & 0xff] + 
    BitsSetTable256[(v >> 8) & 0xff] + 
    BitsSetTable256[(v >> 16) & 0xff] + 
    BitsSetTable256[v >> 24];

// Option 2:
unsigned char * p = (unsigned char *) &v;
c = BitsSetTable256[p[0]] + 
    BitsSetTable256[p[1]] + 
    BitsSetTable256[p[2]] +        
    BitsSetTable256[p[3]];

// To initially generate the table algorithmically:
BitsSetTable256[0] = 0;
for (int i = 0; i < 256; i++)
{
  BitsSetTable256[ i ] = (i & 1) + BitsSetTable256[i / 2];
}

On July 14, 2009 Hallvard Furuseth suggested the macro compacted table.

Counting bits set, Brian Kernighan‘s way

unsigned int v; // count the number of bits set in v
unsigned int c; // c accumulates the total bits set in v
for (c = 0; v; c++)
{
  v &= v - 1; // clear the least significant bit set
}

Brian Kernighan‘s method goes through as many iterations as there are set bits. So if we have a 32-bit word with only the high bit set, then it will only go once through the loop.

Published in 1988, the C Programming Language 2nd Ed. (by Brian W. Kernighan and Dennis M. Ritchie) mentions this in exercise 2-9. On April 19, 2006 Don Knuth pointed out to me that this method "was first published by Peter Wegner in CACM 3 (1960), 322. (Also discovered independently by Derrick Lehmer and published in 1964 in a book edited by Beckenbach.)"

Counting bits set in 14, 24, or 32-bit words using 64-bit instructions

unsigned int v; // count the number of bits set in v
unsigned int c; // c accumulates the total bits set in v

// option 1, for at most 14-bit values in v:
c = (v * 0x200040008001ULL & 0x111111111111111ULL) % 0xf;

// option 2, for at most 24-bit values in v:
c =  ((v & 0xfff) * 0x1001001001001ULL & 0x84210842108421ULL) % 0x1f;
c += (((v & 0xfff000) >> 12) * 0x1001001001001ULL & 0x84210842108421ULL) 
     % 0x1f;

// option 3, for at most 32-bit values in v:
c =  ((v & 0xfff) * 0x1001001001001ULL & 0x84210842108421ULL) % 0x1f;
c += (((v & 0xfff000) >> 12) * 0x1001001001001ULL & 0x84210842108421ULL) % 
     0x1f;
c += ((v >> 24) * 0x1001001001001ULL & 0x84210842108421ULL) % 0x1f;

This method requires a 64-bit CPU with fast modulus division to be efficient. The first option takes only 3 operations; the second option takes 10; and the third option takes 15.

Rich Schroeppel originally created a 9-bit version, similiar to option 1; see the Programming Hacks section of Beeler, M., Gosper, R. W., and Schroeppel, R. HAKMEM. MIT AI Memo 239, Feb. 29, 1972. His method was the inspiration for the variants above, devised by Sean Anderson. Randal E. Bryant offered a couple bug fixes on May 3, 2005. Bruce Dawson tweaked what had been a 12-bit version and made it suitable for 14 bits using the same number of operations on Feburary 1, 2007.

Counting bits set, in parallel

unsigned int v; // count bits set in this (32-bit value)
unsigned int c; // store the total here
static const int S[] = {1, 2, 4, 8, 16}; // Magic Binary Numbers
static const int B[] = {0x55555555, 0x33333333, 0x0F0F0F0F, 0x00FF00FF, 0x0000FFFF};

c = v - ((v >> 1) & B[0]);
c = ((c >> S[1]) & B[1]) + (c & B[1]);
c = ((c >> S[2]) + c) & B[2];
c = ((c >> S[3]) + c) & B[3];
c = ((c >> S[4]) + c) & B[4];

The B array, expressed as binary, is:

B[0] = 0x55555555 = 01010101 01010101 01010101 01010101
B[1] = 0x33333333 = 00110011 00110011 00110011 00110011
B[2] = 0x0F0F0F0F = 00001111 00001111 00001111 00001111
B[3] = 0x00FF00FF = 00000000 11111111 00000000 11111111
B[4] = 0x0000FFFF = 00000000 00000000 11111111 11111111

We can adjust the method for larger integer sizes by continuing with the patterns for the Binary Magic Numbers, B and S. If there are k bits, then we need the arrays S and B to be ceil(lg(k)) elements long, and we must compute the same number of expressions for c as S or B are long. For a 32-bit v, 16 operations are used.

The best method for counting bits in a 32-bit integer v is the following:

v = v - ((v >> 1) & 0x55555555);                    // reuse input as temporary
v = (v & 0x33333333) + ((v >> 2) & 0x33333333);     // temp
c = ((v + (v >> 4) & 0xF0F0F0F) * 0x1010101) >> 24; // count

The best bit counting method takes only 12 operations, which is the same as the lookup-table method, but avoids the memory and potential cache misses of a table. It is a hybrid between the purely parallel method above and the earlier methods using multiplies (in the section on counting bits with 64-bit instructions), though it doesn‘t use 64-bit instructions. The counts of bits set in the bytes is done in parallel, and the sum total of the bits set in the bytes is computed by multiplying by 0x1010101 and shifting right 24 bits.

A generalization of the best bit counting method to integers of bit widths upto 128 (parameterized by type T) is this:

v = v - ((v >> 1) & (T)~(T)0/3);                           // temp
v = (v & (T)~(T)0/15*3) + ((v >> 2) & (T)~(T)0/15*3);      // temp
v = (v + (v >> 4)) & (T)~(T)0/255*15;                      // temp
c = (T)(v * ((T)~(T)0/255)) >> (sizeof(v) - 1) * CHAR_BIT; // count

See Ian Ashdown‘s nice newsgroup post for more information on counting the number of bits set (also known as sideways addition). The best bit counting method was brought to my attention on October 5, 2005 by Andrew Shapira; he found it in pages 187-188 of Software Optimization Guide for AMD Athlon™ 64 and Opteron™ Processors. Charlie Gordon suggested a way to shave off one operation from the purely parallel version on December 14, 2005, and Don Clugston trimmed three more from it on December 30, 2005. I made a typo with Don‘s suggestion that Eric Cole spotted on January 8, 2006. Eric later suggested the arbitrary bit-width generalization to the best method on November 17, 2006. On April 5, 2007, Al Williams observed that I had a line of dead code at the top of the first method.

时间: 2024-08-09 20:10:09

判断一个整数中有多少bit为1的相关文章

判断一个整数不是2的阶次方树

如果是一个2的阶次方,那么它的二进制数的首位一般是1,后面接若干个0.比如8就是1000,64是100 0000. 如果将这个数减1后,再与该数做和&运算,则改全为0. package cn.usst.DataTest; import java.io.*; /** * 从键盘输入一个值 */ public class InputData { static private String s = ""; static public void input() { BufferedRe

判断一个整数是否是2的n次方

参考:http://bbs.csdn.net/topics/370058619 如题,如何判断一个整数是否是2的N次方,我能想到的方法有两个 1.一直除2,看最后是否等于1.(最笨的方法) 2.转换成2进制,看是否是这个样子的:1,10,100,1000,10000,就是除了最高位是1,其他都是0,或者说只有一个1. 3.当我还在为我能想到第二个方法而沾沾自喜的时候,我看到了下面这种更巧妙的方法 以4(100) 7(0111) 8(1000)为例 4 & 3 --> 100 & 01

c语言:判断一个整数是不是2的整数次方

判断一个整数是不是2的整数次方. 解:程序: #include<stdio.h> int count(int t) { int count=0; while (t) { count++; t=t&(t-1); } return count; } int main() { int num,ret=0; printf("请输入一个整数:"); scanf("%d", &num); ret = count(num); if (ret == 1)

判断一个整数是否为另一个整数的幂数

   最近在学习微软推出的虚拟课程中关于网络上最火的20个关于c#的问题,写下关于对于这个问题的个人理解和解决思路,请各位看官笑纳. 题目为:(原)判断一个数字是否2的幂数? 这是我个人还没看正确答案前自己的解决思路(一个小控制台程序),代码如下: static void Main(string[] args) { for (int increment = 0; increment < 100000; increment++) { if (IsPower(increment)) { Consol

经典算法之判断一个整数是否为素数

经典算法之判断一个整数是否为素数 1 /** 2 判断一个数是否为素数 如: 3 输入: 任意一个数 12 4 输出: 1或0(1表示为素数) 0 5 */ 6 /**************被称为笨蛋的做法************/ 7 #include <stdio.h> 8 9 int main() 10 { 11 12 int i,n; //i为计数数,n为存储用户输入的数 13 14 do //循环检测用户输入的数据>0为合法 15 scanf("%d",&

判断一个整数是否是平方数

367. Valid Perfect Square 题意:不用api,判断一个整数是否是平方数. 开始的想法是直接用二分法判断是否是平方数. 错误的代码: 1 public boolean isPerfectSquare(int num) { 2 // binary search 3 int i=0; 4 int n=num; 5 while(i<=n){ 6 int mid=i+(n-i)/2; 7 int square=mid*mid; 8 if(square==num) return tr

判断一个整数是否为回文数 Check if a number is palindrome

一种方法是先翻转当前数,然后把它和原数比较(略) 另一种是递归方法,借用一个复制数,对原数递归,使之翻转,然后配合复制数比较 package recursion; public class Check_if_a_number_is_palindrome { public static void main(String[] args) { int num = 121321; System.out.println(check(num)); num = 12321; System.out.printl

在10000以内判断一个整数,它加上100和加上268后都是一个完全平方数 3 提问:请问该数是多少?

1 ''' 2 在10000以内判断一个整数,它加上100和加上268后都是一个完全平方数 3 提问:请问该数是多少? 4 ''' 5 import math 6 for i in range(10000): 7 m = math.sqrt(i + 100) 8 n = math.sqrt(i + 268) 9 if m * m == i + 100 and n * n == i + 268: 10 print(i) 原文地址:https://www.cnblogs.com/JerryZao/p

判断一个整数是否为素数(质数)

//判断一个整数是否为素数(质数)//质数定义为在大于1的自然数中,除了1和它本身以外不再有其他因数,这样的数称为质数#include <stdio.h>int main(){ int n, i, flag = 0; printf("请输入一个正整数:"); scanf("%d", &n); for (i = 2; i <= n / 2; ++i) { //如果满足以下的条件,他就不是素数 if (n%i == 0) { flag = 1;