Sử dụng stringstream trong C++ để chuyển đổi số thập phân sang chuỗi thập lục phân và ngược lại. Hex là bộ điều khiển I/O.
Ví dụ: Thập phân sang thập lục phân
#include <iostream>
#include <sstream>
using namespace std;
int main() {
int decimal = 61;
stringstream my_ss;
my_ss << hex << decimal;
string res = my_ss.str();
cout << "The hexadecimal value of 61 is: " << res;
return 0;
}
Kết quả
The hexadecimal value of 61 is: 3d
Ví dụ: Thập lục phân sang thập phân
#include <iostream>
#include <sstream>
using namespace std;
int main() {
string hex_str = "0x3d";
unsigned int decimal;
stringstream my_ss;
my_ss << hex << hex_str;
my_ss >> decimal;
cout << "The Decimal value of 0x3d is: " << decimal;
return 0;
}
Kết quả
The Decimal value of 0x3d is: 61