进制转换
1.二进制转十进制
#include <iostream>
#include <string.h>
void main()
{
long int i,len,sum=0;
char str[30];
printf("\n输入二进制数:\n");
gets(str);
len=strlen(str);
for(i=len-1;i>=0;i--)
sum+=(long)(str[i]-'0')<<(len-1-i);
printf("%ld\n",sum);
system("pause");
}
2.获得多少个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)<<endl;
system("pause");
}
#include <iostream>
using namespace std;
int GetIntCount(int n)
{
char Answer[8*sizeof(int)+1];
static int LEN=8*sizeof(int);
for (int i = LEN - 1; i >= 0; i--, n >>= 1)
Answer[i] = (01 & n) + '0';
Answer[LEN] = '\0';
string Str = Answer;
int nCount=0;
for(int i=0;i<LEN;i++)
{
if(1==Str[i]-48)
nCount++;
}
return nCount;
}
void main()
{
cout<<GetIntCount(7)<<endl;
system("pause");
}
3.十进制转二进制
#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;
}
void main()
{
int v[]={7,256};
char b[8*sizeof(int)+1];
int i=-1;
while(++i<sizeof(v)/sizeof(v[0]))
cout<<ok(v[i],b)<<endl;
system("pause");
}
#include <stdlib.h>
#include <stdio.h>
int Fuc(int bin)
{
int lln=1;
int dec=0 ;
while (bin)
{
dec+=bin%10*lln;
lln*=2;
bin/=10;
}
return dec;
}
int main(void)
{
int number = 256;
char string[25];
printf("%d\n",number);
itoa(number, string, 2);
printf("%s\n",string);
number = atoi(string);
printf("%d\n",Fuc(number));
system("pause");
return 0;
}