65,211
社区成员
发帖
与我相关
我的任务
分享
/*
十进制转二进制:
用2辗转相除至结果为1
将余数和最后的1从下向上倒序写 就是结果
例如302
302/2 = 151 余0
151/2 = 75 余1
75/2 = 37 余1
37/2 = 18 余1
18/2 = 9 余0
9/2 = 4 余1
4/2 = 2 余0
2/2 = 1 余0
故二进制为100101110
二进制转十进制
从最后一位开始算,依次列为第0、1、2...位
第n位的数(0或1)乘以2的n次方
得到的结果相加就是答案
例如:01101011.转十进制:
第0位:1乘2的0次方=1
1乘2的1次方=2
0乘2的2次方=0
1乘2的3次方=8
0乘2的4次方=0
1乘2的5次方=32
1乘2的6次方=64
0乘2的7次方=0
然后:1+2+0
+8+0+32+64+0=107.
二进制01101011=十进制107.
*/
#include <iostream>
using namespace std;
class BinarySystem
{
public:
BinarySystem( int number );
int bCout();
private:
int rNum;
};
BinarySystem::BinarySystem( int number )
{
rNum = 0;
int result(number),residue(0);
while( result != 1 )
{
result = result / 2 ;
residue = number % 2;
if( residue == 1 )
++rNum;
}
}
int BinarySystem::bCout()
{
rNum += 1 ;
return rNum;
}
int main()
{
cout << "Please insert a number " << endl;
int a,b;
cin >> a;
BinarySystem binary( a );
b = binary.bCout();
cout << "The number is " << b << endl;
system("pause");
}
#include <iostream>
using namespace std;
template <int num>
struct bit1_count{
enum { result = (num & 1 == 1 ? 1 : 0) + bit1_count<(num >> 1)>::result};
};
template <>
struct bit1_count<0> {
enum { result = 0 };
};
int main() {
cout << bit1_count<1>::result << endl;
cout << bit1_count<2>::result << endl;
cout << bit1_count<3>::result << endl;
cout << bit1_count<7>::result << endl;
cout << bit1_count<1024>::result << endl;
::system("PAUSE");
return 0;
}
#include <iostream>
using namespace std;
inline int bit_one_count(int i) {
int num = 0;
while (0 != i) {
num += i & 1 ? 1 : 0;
i >>= 1;
}
return num;
};
int main() {
cout << bit_one_count(1) << endl;
cout << bit_one_count(2) << endl;
cout << bit_one_count(3) << endl;
cout << bit_one_count(1024) << endl;
::system("PAUSE");
return 0;
}
#include <stdio.h>
// Hacker's Delight, 5-1
// Figure 5-2 Counting 1-bits in a word.
int pop(unsigned x) {
x = x - ((x >> 1) & 0x55555555);
x = (x & 0x33333333) + ((x >> 2) & 0x33333333);
x = (x + (x >> 4)) & 0x0F0F0F0F;
x = x + (x >> 8);
x = x + (x >> 16);
return x & 0x0000003F;
}
int main()
{
unsigned long x;
while (1)
{
printf("input an integer: ");
scanf("%d", &x);
if (x == 0)
break;
printf("0x%08X: Number of 1-bits: %d\n", x, pop(x));
}
return 0;
}
int bit_count(unsigned int n)
{
int count;
for(count=0; n; n&= n- 1)
count++;
return count;
}
void main()
{
unsigned int n;
int cnt;
cout <<"Input your num:" <<endl;
cin>>n;
cnt=bit_count(n);
cout <<"count num of bits :" <<cnt <<endl;
}