yongde1990
2018-03-21 22:00:55
c语言实现IP地址转换为16进制输出
输入 : 1.168.229.200
输出 :0x01 0xa8 0xe5 0xc8
#include <arpa/inet.h> #include <netinet/in.h> #include <iomanip> #include <bitset> #include <sstream> #include<stdio.h> #include<stdlib.h> string ip_to_hex_str(const string& ip) { char* ch_ip = const_cast<char*>(ip.c_str()); struct in_addr ia_ip; char hex_ip[8]={0}; unsigned long long_ip; long_ip=inet_addr(ch_ip); for(int i=0; i < 4;i++) { sprintf(hex_ip+(i*2),"%02x",*((unsigned char*)(&long_ip)+i)); } ostringstream ost_des; ost_des << "0x" << hex_ip[0] << hex_ip[1] << " 0x" << hex_ip[2] << hex_ip[3] << " 0x" << hex_ip[4] << hex_ip[5] << " 0x" << hex_ip[6] << hex_ip[7]; return ost_des.str(); } int main(int argc, char ** argv) { string str1 = "1.168.229.200"; cout<< ip_to_hex_str(str1) << endl; return 0; }
评论
最近浏览


