Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1710956
  • 博文数量: 143
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 1462
  • 用 户 组: 普通用户
  • 注册时间: 2016-08-23 11:14
文章分类

全部博文(143)

文章存档

2022年(3)

2021年(13)

2020年(21)

2019年(8)

2018年(28)

2017年(7)

2016年(63)

我的朋友

分类: 嵌入式

2018-10-08 23:34:55

strtok()
  strtok()的用法:

点击(此处)折叠或打开

  1. pstr = strtok(str, ".");
  2. while(pstr != NULL)
  3. {
  4.     ip[i] = (unsigned char)atoi(pstr);
  5.     
  6.     i++;
  7.     pstr = strtok(NULL, ".");
  8. }
  另外,我们还可以使用sscanf()来解析一些特定字符串,如mac和ip

sscanf()
  sscanf()的举例:
  1.2str

点击(此处)折叠或打开

  1. #define MACSTR "%02x:%02x:%02x:%02x:%02x:%02x"
  2. #define MAC2STR (a[0]&0xff), (a[1]&0xff), (a[2]&0xff), (a[3]&0xff), (a[4]&0xff), (a[5]&0xff)

点击(此处)折叠或打开

  1. ntohl(a);
  2. #define IPSTR "%u.%u.%u.%u"
  3. #define IP2STR(a) (a >> 24 &0xff), (a >> 16 &0xff), (a >> 8 &0xff), (a&0xff)
  2.str2

点击(此处)折叠或打开

  1. #define STR2MAC(str_mac, dest_mac) sscanf(str_mac, "%02x:%02x:%02x:%02x:%02x:%02x", dest_mac, dest_mac+1, dest_mac+2, dest_mac+3, dest_mac+4, dest_mac+5)

点击(此处)折叠或打开

  1. #define STR2IP(str_ip, dest_ip) sscanf(str_ip, "%u.%u.%u.%u", dest_ip, dest_ip+1, dest_ip+2, dest_ip+3)
  这2种写法都是错误的,是踩内存的,(即使恰巧结果是对的,也仅仅是因为所踩到的内存无关要紧罢了)。不信试着这样写:

点击(此处)折叠或打开

  1. #define STR2MAC(str_mac, dest_mac) sscanf(str_mac, "%02x:%02x:%02x:%02x:%02x:%02x", dest_mac+5, dest_mac+4, dest_mac+3, dest_mac+2, dest_mac+1, dest_mac)

点击(此处)折叠或打开

  1. #define STR2IP(str_ip, dest_ip) sscanf(str_ip, "%u.%u.%u.%u", dest_ip+3, dest_ip+2, dest_ip+1, dest_ip)
  就会发现结果错误。这是因为sscanf()的format中,要求必须严格输入,而这里%02x和%u都要求是32bit的,但输入的dest_mac和dest_ip却是unsigned char*。所以正确的宏定义:

点击(此处)折叠或打开

  1. #define STR2MAC(str_mac, dest_mac)\
  2. do{\
  3.     unsigned int tmp_mac[6];\
  4.     if(sscanf(str_mac, "%02x:%02x:%02x:%02x:%02x:%02x", tmp_mac, tmp_mac+1, tmp_mac+2, tmp_mac+3, tmp_mac+4, tmp_mac+5) == 6){\
  5.         dest_mac[0] = (unsigned char)tmp_mac[0];\
  6.         dest_mac[1] = (unsigned char)tmp_mac[1];\
  7.         dest_mac[2] = (unsigned char)tmp_mac[2];\
  8.         dest_mac[3] = (unsigned char)tmp_mac[3];\
  9.         dest_mac[4] = (unsigned char)tmp_mac[4];\
  10.         dest_mac[5] = (unsigned char)tmp_mac[5];\
  11.     }\
  12. }while(0)

点击(此处)折叠或打开

  1. #define STR2IP(str_ip, dest_ip)\
  2. do{\
  3.     unsigned int tmp_ip[4];\
  4.     if(sscanf(str_ip, "%u.%u.%u.%u", tmp_ip, tmp_ip+1, tmp_ip+2, tmp_ip+3) == 4){\
  5.         *dest_ip = (tmp_ip[0]<<24) + (tmp_ip[1]<<16) + (tmp_ip[2]<<8) + tmp_ip[3];
  6.     }\
  7. }while(0)
阅读(4323) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~