十进制正整数与二进制字符串的转换(C++)

  • Post author:
  • Post category:其他


Function one:

//十进制数字转成二进制字符串
string Binary(int x) 
{
    string s = "";
    while(x){
        if(x % 2 == 0) s = '0' + s;
        else s = '1' + s;
        x /= 2;
    }
    return s;
}

Function two:

//二进制字符串变为十进制数字
int Decimal(string s)  
{
     int num = 0, len = s.length() - 1;
     for(int i = 0; s[i]; i++){
        if(s[i] == '1')  num += pow(2, len - i);
     }
     return num;
}

Run:

#include<bits/stdc++.h>
using namespace std;
//十进制数字转成二进制字符串
string Binary(int x) 
{
    string s = ""; //定义空字符串,那么如果输入x=0,则返回值为空
    while(x){
        if(x % 2 == 0) s = '0' + s;
        else s = '1' + s;
        x /= 2;
    }
    return s;
}
//二进制字符串变为十进制数字
int Decimal(string s)  
{
     int num = 0, len = s.length() - 1;
     for(int i = 0; s[i]; i++){
        //利用pow函数实现次幂运算
        if(s[i] == '1')  num += pow(2, len - i);
     }
     return num;
}
int main(void)
{
    int num;
    string s;
    cin >>num; 
    cout <<Binary(num) <<endl;  //二进制字符串输出
    cout <<Decimal(Binary(num)) <<endl; //转回十进制
    cin >>s;
    cout <<Decimal(s) <<endl;  //输出s对应的十进制数
    return 0;
}

Result:



版权声明:本文为qq_59700927原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。