〈一〉二进制转化为各个进制的操作
#include <iostream>
#include <bitset>
#include <sstream>
int main() {
// 二进制数
std::string binaryStr = "1010101010";
// 将二进制字符串转换为十进制数
std::bitset<sizeof(unsigned long) * 8> binary(binaryStr);
unsigned long decimal = binary.to_ulong();
// 将十进制数转换为八进制数
std::stringstream octStream;
octStream << std::oct << decimal;
std::string octalStr = octStream.str();
// 将十进制数转换为十六进制数
std::stringstream hexStream;
hexStream << std::hex << decimal;
std::string hexStr = hexStream.str();
std::cout << "Binary: " << binaryStr << std::endl;
std::cout << "Decimal: " << decimal << std::endl;
std::cout << "Octal: " << octalStr << std::endl;
std::cout << "Hexadecimal: " << hexStr << std::endl;
return 0;
}
〈二〉八进制转化为各个进制的操作
#include <iostream>
#include <sstream>
int main() {
// 八进制数
std::string octalStr = "1234567";
// 将八进制字符串转换为十进制数
std::stringstream octStream;
octStream << std::oct << octalStr;
unsigned long decimal;
octStream >> decimal;
// 将十进制数转换为二进制数
std::string binaryStr = std::bitset<sizeof(unsigned long) * 8>(decimal).to_string();
// 将十进制数转换为十六进制数
std::stringstream hexStream;
hexStream << std::hex << decimal;
std::string hexStr = hexStream.str();
std::cout << "Octal: " << octalStr << std::endl;
std::cout << "Decimal: " << decimal << std::endl;
std::cout << "Binary: " << binaryStr << std::endl;
std::cout << "Hexadecimal: " << hexStr << std::endl;
return 0;
}
〈三〉十进制转化为各个进制的操作
#include <iostream>
#include <bitset>
#include <sstream>
int main() {
// 十进制数
unsigned long decimal = 123456;
// 将十进制数转换为二进制数
std::string binaryStr = std::bitset<sizeof(unsigned long) * 8>(decimal).to_string();
// 将十进制数转换为八进制数
std::stringstream octStream;
octStream << std::oct << decimal;
std::string octalStr = octStream.str();
// 将十进制数转换为十六进制数
std::stringstream hexStream;
hexStream << std::hex << decimal;
std::string hexStr = hexStream.str();
std::cout << "Decimal: " << decimal << std::endl;
std::cout << "Binary: " << binaryStr << std::endl;
std::cout << "Octal: " << octalStr << std::endl;
std::cout << "Hexadecimal: " << hexStr << std::endl;
return 0;
}
〈四〉十六进制转化为各个进制的操作
#include <iostream>
#include <bitset>
#include <sstream>
int main() {
// 十六进制数
std::string hexStr = "2021ABCD";
// 将十六进制字符串转换为十进制数
std::stringstream ss;
ss << std::hex << hexStr;
unsigned long decimal;
ss >> decimal;
// 将十六进制数转换为二进制数
std::bitset<sizeof(unsigned long) * 8> binary(decimal);
std::string binaryStr = binary.to_string();
// 将十六进制数转换为八进制数
std::stringstream octStream;
octStream << std::oct << decimal;
std::string octalStr = octStream.str();
std::cout << "Hexadecimal: " << hexStr << std::endl;
std::cout << "Binary: " << binaryStr << std::endl;
std::cout << "Octal: " << octalStr << std::endl;
return 0;
}