C语言字符串十进制IP地址与十六进制转换

C语言字符串十进制IP地址与十六进制转换

提示:for循环太low了,代码用位运算

1、
输入:192.168.1.155
输出:0xc0a8019b

#include 
#include 
#include 
unsigned int Covert(char *message)
{
	char *p[4] = {0};
	char *last;
	p[0] = strtok_r(message, ".", &last);
	p[1] = strtok_r(NULL, ".", &last);
	p[3] = strtok_r(NULL, ".", &last);
	return (atoi(p[0])<<24) | (atoi(p[1])<<16) | (atoi(p[2])<<8);
}
int main()
{
	char message[32] = {0};
	strcpy(message, "192.168.1.155");
	printf("10进制的ip地址是:%s\n", message);
	printf("16进制的ip地址是:%s\n"Covert(message));
	return 0;
}

我是用linux环境下gcc编译的,只需敲入命令
gcc test.cc -o test
./test

2、
输入:0xc0a8019b
输出:192.168.1.155

这里我提供三种方法,由于都是位运算,代码执行效率很高。那么根据代码简洁程度不同,我个人倾向于第三种。

#include 
#include 
#include 
unsigned int change1(unsigned int ip, char *mm)
{
	sprintf(mm, "%d.%d.%d.%d", (unsigned char)(ip>>24), (unsigned char)(ip>>16), (unsigned char)(ip>>8),(unsigned char)ip );
}
unsigned int change2(unsigned int ip, char *mm)
{
	sprintf(mm, "%d.%d.%d.%d", (ip & 0xff000000)>>24, ip & 0xff0000)>>16, (ip & 0xff00)>>8,(ip & 0xff);
}
unsigned int change3(unsigned int ip, char *mm)
{
	sprintf(mm, "%d.%d.%d.%d", (ip>>24) & 0xff, (ip>>16) & 0xff, (ip>>8) & 0xff, ip &0xff);
}
int main()
{
	char message[32] = {0};
	change1(0xc0a8019b, message);
	printf("10进制的ip地址是:%s\n", message);
	return 0;
}

注意:位运算很强大,建议大家多用位运算解决问题。

你可能感兴趣的:(C语言,C++,算法,c语言)