บทนำ
ในส่วนนี้เราจะดูวิธีแปลง Decimal เป็น Hexadecimal string และจาก Hexadecimal string กลับเป็น Decimal ใน C++ โดยใช้ stringstream
String streams ใช้สำหรับ formatting, parsing, แปลงสตริงเป็นค่าตัวเลข เป็นต้น Hex เป็น IO manipulator รับ reference ของ IO stream คืน reference ของสตริงหลังจัดการ
ตัวอย่าง Decimal เป็น Hex
#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;
}
ผลลัพธ์
The hexadecimal value of 61 is: 3d
ตัวอย่าง Hex เป็น Decimal
#include <iostream>
#include <sstream>
using namespace std;
int main() {
string hex_str = "0x3d"; // อาจใส่ 0x หรือไม่ก็ได้
unsigned int decimal;
stringstream my_ss;
my_ss << hex << hex_str;
my_ss >> decimal;
cout << "The Decimal value of 0x3d is: " << decimal;
return 0;
}
ผลลัพธ์
The Decimal value of 0x3d is: 61