一、数值转十进制字符串
- 使用
to_string
方法
#include <iostream>
#include <string>using namespace std;int main() {int num = 42;string decStr = to_string(num);cout << decStr << endl;return 0;
}
# 输出结果42
- 使用字符串流
#include <iostream>
#include <string>
#include <sstream>using namespace std;int main() {int num = 42;ostringstream oss;oss << num;string decStr = to_string(num);cout << decStr << endl;return 0;
}
# 输出结果42
二、数值转八进制字符串
#include <iostream>
#include <string>
#include <sstream>using namespace std;int main() {int num = 42;ostringstream oss;oss << oct << num;string octStr = oss.str();cout << octStr << endl;return 0;
}
# 输出结果52
三、数值转二进制字符串
1、转换并补零
#include <iostream>
#include <string>
#include <bitset>using namespace std;int main() {int num = 42;string binStr = bitset<8>(num).to_string();cout << binStr << endl;return 0;
}
# 输出结果00101010
2、转换不补零
- 使用
find_first_not_of
方法跳过前导 0
#include <iostream>
#include <string>
#include <bitset>using namespace std;int main() {int num = 42;string binStr = bitset<8>(num).to_string();size_t firstNonZero = binStr.find_first_not_of('0');if (firstNonZero == string::npos) {firstNonZero = binStr.size() - 1;}binStr = binStr.substr(firstNonZero);cout << binStr << endl;return 0;
}
# 输出结果101010
- 手动计算二进制
#include <iostream>
#include <string>
#include <algorithm>using namespace std;string intToBinary(int num) {if (num == 0) return "0";string binStr;while (num > 0) {binStr += (num % 2) ? '1' : '0';num /= 2;}reverse(binStr.begin(), binStr.end()); return binStr;
}int main() {int num = 42;string binStr = intToBinary(num);cout << binStr << endl;return 0;
}
# 输出结果101010
四、数值转十六进制字符串
1、基本转换
#include <iostream>
#include <string>
#include <sstream>using namespace std;int main() {int num = 42;ostringstream oss;oss << hex << num;string hexStr1 = oss.str();oss.str("");oss << uppercase << hex << num;string hexStr2 = oss.str();cout << hexStr1 << endl;cout << hexStr2 << endl;return 0;
}
# 输出结果2a
2A
2、补零
- 使用字符串流 + setw 方法 + setfill 方法
#include <iostream>
#include <string>
#include <sstream>
#include <iomanip>using namespace std;int main() {int num = 42;ostringstream oss;oss << hex << setw(4) << setfill('0') << num;string hexStr1 = oss.str();oss.str("");oss << uppercase << hex << setw(4) << setfill('0') << num;string hexStr2 = oss.str();cout << hexStr1 << endl;cout << hexStr2 << endl;return 0;
}
# 输出结果002a
002A