联合体的巧妙实用

本文介绍了如何使用sprintf_s()和sscanf_f()进行十进制数到IP地址字符串和反之的转换。首先,通过Uint_To_Str2()函数展示了十进制转IP的简洁方法,然后提供了一个冗长但未完成的Uint_To_Str()函数。接着,Str_To_Uint()函数演示了IP地址解析为十进制的过程。
摘要由CSDN通过智能技术生成

sprintf_s(),sscanf_f()的使用
十进制数和IP地址的相互转化
十进制数转化成IP地址字符串

#include<stdio.h>
#include<stdlib.h>
#include<assert.h>
#include<string.h>
union IPNode
{
	int addr;
	unsigned char s[4];
};
void Uint_To_Str2(char* buff, int len, unsigned int ip)//巧妙解法
{
	assert(buff != NULL);
	IPNode x;
	x.addr = ip;
	sprintf_s(buff, len, "%d.%d.%d.%d", x.s[3], x.s[2], x.s[1], x.s[0]);
}
void Uint_To_Str(char* buff, unsigned int ip)//麻烦方法思路没有实现
{
	assert(buff != NULL);
	unsigned char x;
	char str[10];
	for (int i = 0; i < sizeof(unsigned int); ++i)
	{
		x = ip & 0x000000ff;
		ip = ip >> 8
		_itoa_s(3, str, 10);
		strcpy(buff,str);
	}
}
int main()
{
	char buff[20];
	unsigned int ip = 2148205343;
	Uint_To_Str2(buff,20, ip);
	printf("%s", buff);
	return 0;
}

IP地址转化成十进制数

union IPNode
{
	int addr;
	unsigned char sx[4];
};
int Str_To_Uint(char *stra)
{
	IPNode x;
	int s[4];
	char ch;
	int n = sscanf_s(stra, "%d.%d.%d.%d%c", &s[3], &s[2], &s[1], &s[0], &ch);
	if (n != 4) return -1;
	for (int i = 3; i >= 0; --i)
	{
		if (s[i] >= 0 && s[i] <= 255)
		{
			x.sx[i] = s[i];
		}
		else
		{
			printf("error\n");
			return -1;
		}
	}
	return x.addr;
}
int main()
{
	char stra[] = { "128.11.3.31" };
 	char strb[] = { "128.11.3.31.156" };
	char strc[] = { "128.3.22" };
	unsigned int ip = Str_To_Uint(stra);
	printf("%u\n", ip);
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值