获得二进制有多少个1

 

#include <iostream>
using namespace std;
char *ok(int n,char *b) 

 static int LEN=8*sizeof(int); 
 for(int i=LEN-1;i>=0;i--,n>>=1) 
  b[i]=(01&n)+'0'; 
 b[LEN]='\0'; 
 return b; 

int GetIntCount(string b)
{
 int nCount=0;
 static int LEN=8*sizeof(int);
 for(int i=0;i<LEN;i++)
 {
  if(1==b[i]-48)
   nCount++;
 }
 return nCount;
}

void main() 

 int v=255; 
 char b[8*sizeof(int)+1]; 
 int i=-1; 
 string s=ok(v,b);
 cout<<ok(v,b)<<endl;
 cout<<GetIntCount(s);
 getchar();
}

posted @ 2011-12-13 14:56  byfei  阅读(143)  评论(0编辑  收藏  举报