进制转换(这也太香了吧,爱了爱了->^^<-)

十进制转二进制:

#include <iostream>
#include <bitset>

using namespace std;

int main() {
    int x;
    while(cin >> x) { // 读取十进制数
        bitset<32> bits(x); // 将十进制数转换为bitset
        cout << bits << endl; // 输出对应的二进制数
    }
    return 0;
}
记忆方法十进制的英文decimal

十进制转八进制:

#include <iostream>

using namespace std;

int main() {
    int x;
    while(cin >> x) { // 读取十进制数
        cout << oct << x << endl; // 转换为八进制并输出
    }
    return 0;
}
记忆方法:octal八进制 八爪鱼英文单词octopus取其前缀oct八进制

十进制转十六进制:

#include <iostream>

using namespace std;

int main() {
    int x;
    while(cin >> x) { // 读取十进制数
        cout << hex << x << endl; // 转换为十六进制并输出
    }
    return 0;
}

二进制转十进制:

#include <iostream>  
#include <string>  
#include <bitset> // C++11 及以上版本提供了 bitset  
  
using namespace std;  
  
int main()  
{  
    string binaryStr;  
    while (cin >> binaryStr) // 直接读取字符串  
    {  
        // 使用 bitset 转换二进制字符串到十进制数(需要 C++11 或更高版本)  
        bitset<32> bits(binaryStr); // 假设二进制字符串不超过 32 位  
        int decimal = bits.to_ulong(); // 转换为无符号长整型(如果确定不会溢出)  
        // 如果要转换为 int 类型并且担心溢出,可以手动处理或者使用 bitset<31> 等更小的位数  
  
        cout << decimal << endl;  
    }  
    return 0;  
}

八进制转十进制:

#include <iostream>
#include <bitset>

using namespace std;

int main()
{
    int x;
    while(cin >> oct >> x) // 如果要读取八进制数,使用 std::oct
    {
        cout << x << endl;
    }
    return 0;
}

十六进制转十进制:

#include <iostream>
#include <cstring>
#include <algorithm>

using namespace std;

int main()
{
   int x;
   while(cin >> hex >> x)
   {
       cout << x << endl;
   }
    return 0;
}

  • 6
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值