(一)共用体
( 二)共用体的作用
(1)节省空间 (2)对同一块空间进行不同类型的识别
(三)共用体的应用
(1)IP地址是unsigned int 类型,请将其转成点分十进制输出
#include <stdio.h>
union Ip_addr
{
unsigned int addr;
struct
{
unsigned char s1;
unsigned char s2;
unsigned char s3;
unsigned char s4;
};
};
char* IP_addrToStr(unsigned int ip, char* buff)
{
if(ip < 0 || buff == NULL)
return NULL;
union Ip_addr tmp;
tmp.addr = ip;
sprintf(buff, "%d.%d.%d.%d", tmp.s4, tmp.s3, tmp.s2, tmp.s1);
return buff;
}
int main()
{
unsigned int ip = 2130706433;
char buff[32] = {0};
printf("%s\n", IP_addrToStr(ip, buff));
return 0;
}
(2)将字符串的ip地址转成unsigned int类型
#pragma warning(disable : 4996)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
union Ip_addr
{
unsigned int addr;
struct
{
unsigned char s[4];
};
};
unsigned int StrToIP_addr_s(char* ip_str)
{
if (ip_str == NULL)
return -1;
union Ip_addr tmp = { 0 };
char buff[32] = { 0 };
strcpy(buff, ip_str);
sscanf(ip_str, "%hhu.%hhu.%hhu.%hhu", &tmp.s[3], &tmp.s[2], &tmp.s[1], &tmp.s[0]);
return tmp.addr;
}
unsigned int StrToIP_addr(char* ip_str)
{
if (ip_str == NULL)
return -1;
union Ip_addr tmp = { 0 };
int i = 3;
char buff[32] = { 0 };
strcpy(buff, ip_str);
char* s = strtok(buff, ".");
while (s != NULL)
{
tmp.s[i--] = atoi(s);
s = strtok(NULL, ".");
}
return tmp.addr;
}
int main()
{
printf("ip1 = %d\n", StrToIP_addr("127.0.0.1"));
printf("ip2 = %d\n", StrToIP_addr_s("127.0.0.1"));
return 0;
}
- vs2019结果:
- mingw32-gcc-g++:结果异常(懂得大神还请指正出来 TvT)
|