📄 bin_to_dec.cpp
字号:
#include <iostream>
#include <string>
#include <fstream>
#include <vector>
#include <time.h>
using namespace std;
//-----------------------------------------
void add(char a[],char b[],char c[]);
void clear(char result[]);
void input();
int i,j;
int main(){
char decimal[20];
char pow[64][20];
input();
//initialization
for(i=0;i<64;i++)
for(j=0;j<20;j++){
decimal[j]='0';
pow[i][j]='0';
}
pow[0][0]='1';
for(i=1;i<64;i++)
add(pow[i-1],pow[i-1],pow[i]); //get the 1! 2!......64!,store them in pow[64][]
clock_t t=clock();
//if you want to test the sample binary data in our textbook,use "test.txt" instead
ifstream in("change.in.txt");
string s;
bool flag=true;
for (;getline(in,s);){
if(s=="-1") break;
//change into the decimal
int k=0;
for(int i=s.length()-1;i>=0;i--,k++)
if(s.at(i)=='1') add(decimal,pow[k],decimal);
//output the decimal
for(j=19;j>=0;j--)
if( (decimal[j]=='0') && flag) continue;
else { cout<<decimal[j]; flag=false;}
if(flag) cout<<'0';
cout<<"\n";
clear(decimal);
flag=true;
}
cout<<"\nUsing "<<(clock()-t)/CLK_TCK<<" seconds\n";
}//end of main
/* char a[]+ char b[]=char c[] */
void add(char a[],char b[],char c[]){
int digit=0,carry=0,bitsum=0;
while(digit<20){
bitsum=a[digit]+b[digit]-96+carry;
if(bitsum>9) carry=1;
else carry=0;
c[digit]=bitsum%10+48;
digit++;
}
}
/*clear the decimal[]*/
void clear(char result[]){
for(int k=0;k<20;k++)
result[k]='0';
}
void input(){
ofstream out("change.in.txt");
for(i=0;i<3000;i++){
int digits=rand()%64+1;
for(j=0;j<digits;j++)
out<<rand()%2;
out<<endl;
}
out<<"-1";
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -