- C++进制之间的转换
- 1.初阶篇
- 1.1 10 进制与 2 进制
- 1.1.1 10进制转2进制
- 1.1.2 2进制转10进制
- 1.2 10 进制与 8 进制
- 1.2.1 10进制转8进制
- 1.2.2 8进制转10进制
- 1.3 10 进制与16进制
- 1.3.1 10进制转16进制
- 1.3.2 16进制转10进制
- 2.进阶篇
- 2.1 10进制与任意进制
- 2.1.1 10进制与任意进制
- 2.1.2 任意进制转10进制
- 2.2 2进制与8/16进制
- 2.2.1 2进制与8进制
- 2.2.2 2进制与16进制
//方法一:普通转换
std::string IntToBinary(int intx) {
std::string binary = "";
int a = intx;
while(a) {
binary = std::to_string(a % 2) + binary;
a /= 2;
}
return binary;
}
//方法二:递归方法
std::string IntToBinary(int intx) {
std::string binary = "";
int temp = intx / 2;
int left = intx % 2;
if (temp > 0) {
binary += IntToBinary(temp);
}
if (left < 2 ) {
binary += (left + '0');
}
else {
binary += (left - 2);
}
return binary;
}
1.1.2 2进制转10进制
//2进制转10进制
int IntFromBinary(std::string str) {
int count = 0;
int num = (int)str.size() - 1;
for (unsigned i = 0; i < str.size(); i++) {
count += ((str[i] - 48) * std::pow(2, num));
num--;
}
return count;
}
1.2 10 进制与 8 进制
1.2.1 10进制转8进制
//递归法:10进制转8进制
std::string IntToOctal(int intx) {
std::string octal = "";
int temp = intx / 8;
int left = intx % 8;
if (temp > 0) {
octal += IntToOctal(temp);
}
if (left < 8 ) {
octal += (left + '0');
}
else {
octal += (left - 8);
}
return octal;
}
1.2.2 8进制转10进制
int IntFromOctal(std::string str) {
int count = 0;
int num = (int)str.size() - 1;
for (unsigned i = 0; i < str.size(); i++) {
count += ((str[i] - 48) * std::pow(8, num));
num--;
}
return count;
}
1.3 10 进制与16进制
1.3.1 10进制转16进制
//递归法:10进制转16进制
std::string IntToHex(int intx) {
std::string hexadecimal = "";
int temp = intx / 16;
int left = intx % 16;
if (temp > 0) {
hexadecimal += IntToHex(temp);
}
if (left < 10 ) {
hexadecimal += (left + '0');
}
else {
hexadecimal += ('A' + left - 10);
}
return hexadecimal;
}
1.3.2 16进制转10进制
int IntFromOctal(std::string str) {
int count = 0;
int num = (int)str.size() - 1;
for (unsigned i = 0; i < str.size(); i++) {
count += ((str[i] - 48) * std::pow(16, num));
num--;
}
return count;
}
2.进阶篇
2.1 10进制与任意进制
2.1.1 10进制与任意进制
2.1.2 任意进制转10进制
//任意进制转10进制
int InverseConvert() {
std::string str = ui->input_linedit->text().toStdString();
int num = (int)str.size() - 1;
for (unsigned i = 0; i < str.size(); i++) {
output += ((str[i] - 48) * std::pow(bit_state, num));
num--;
}
}
return output;
2.2 2进制与8/16进制
2.2.1 2进制与8进制
2.2.2 2进制与16进制
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)