十进制转二进制:
#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;
}