以下是将std::string类型的IPv4地址转换为四个十六进制数字的示例代码:
#include <iostream>
#include <sstream>
#include <iomanip>
int main() {
std::string ipv4 = "192.168.0.1";
std::istringstream iss(ipv4);
int a, b, c, d;
char dot1, dot2, dot3;
iss >> a >> dot1 >> b >> dot2 >> c >> dot3 >> d;
if (dot1 == '.' && dot2 == '.' && dot3 == '.') {
std::cout << std::hex << std::setw(2) << std::setfill('0') << a << " "
<< std::hex << std::setw(2) << std::setfill('0') << b << " "
<< std::hex << std::setw(2) << std::setfill('0') << c << " "
<< std::hex << std::setw(2) << std::setfill('0') << d << std::endl;
}
return 0;
}
输出结果:
c0 a8 00 01
解释:
首先将字符串形式的IP地址 192.168.0.1
存储在变量 ipv4
中。
使用 std::istringstream
对 ipv4
进行分割和解析,并将每一个整数存储在变量 a,b,c,d
中,以及每一个点号.
存储在变量 dot1,dot2,dot3
中。
最后,将每个整数转换成两位的十六进制数,并用空格隔开输出。