Chinaunix首页 | 论坛 | 博客
  • 博客访问: 3977446
  • 博文数量: 366
  • 博客积分: 9916
  • 博客等级: 中将
  • 技术积分: 7195
  • 用 户 组: 普通用户
  • 注册时间: 2011-05-29 23:27
个人简介

简单!

文章分类

全部博文(366)

文章存档

2013年(51)

2012年(269)

2011年(46)

分类: C/C++

2013-07-01 22:26:57

在标准C中,isdigit函数可以用来判断字符是否为0~9之间的数字。比如:
  1. int a = isdigit('1');
  2. int b = isdigit('a');
  3. int c = isdigit(3);
可以使用宏定义去实现这个简单的函数,如下所示:
  1. #define isdigit(c) ((c) >= '0' && (c) <= '9')

Linux内核中isdigit的实现,其代码如下所示:
  1. #define _U 0x01 /* upper */
  2. #define _L 0x02 /* lower */
  3. #define _D 0x04 /* digit */
  4. #define _C 0x08 /* cntrl */
  5. #define _P 0x10 /* punct */
  6. #define _S 0x20 /* white space (space/lf/tab) */
  7. #define _X 0x40 /* hex digit */
  8. #define _SP 0x80 /* hard space (0x20) */
  9.  
  10. extern unsigned char _ctype[];

  11. #define isdigit(c) ((_ctype+1)[c]&(_D))

  12. unsigned char _ctype[] = {0x00, /* EOF */
  13.  _C,_C,_C,_C,_C,_C,_C,_C, /* 0-7 */
  14.  _C,_C|_S,_C|_S,_C|_S,_C|_S,_C|_S,_C,_C, /* 8-15 */
  15.  _C,_C,_C,_C,_C,_C,_C,_C, /* 16-23 */
  16.  _C,_C,_C,_C,_C,_C,_C,_C, /* 24-31 */
  17.  _S|_SP,_P,_P,_P,_P,_P,_P,_P, /* 32-39 */
  18.  _P,_P,_P,_P,_P,_P,_P,_P, /* 40-47 */
  19.  _D,_D,_D,_D,_D,_D,_D,_D, /* 48-55 */
  20.  _D,_D,_P,_P,_P,_P,_P,_P, /* 56-63 */
  21.  _P,_U|_X,_U|_X,_U|_X,_U|_X,_U|_X,_U|_X,_U, /* 64-71 */
  22.  _U,_U,_U,_U,_U,_U,_U,_U, /* 72-79 */
  23.  _U,_U,_U,_U,_U,_U,_U,_U, /* 80-87 */
  24.  _U,_U,_U,_P,_P,_P,_P,_P, /* 88-95 */
  25.  _P,_L|_X,_L|_X,_L|_X,_L|_X,_L|_X,_L|_X,_L, /* 96-103 */
  26.  _L,_L,_L,_L,_L,_L,_L,_L, /* 104-111 */
  27.  _L,_L,_L,_L,_L,_L,_L,_L, /* 112-119 */
  28.  _L,_L,_L,_P,_P,_P,_P,_C, /* 120-127 */
  29.  0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, /* 128-143 */
  30.  0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, /* 144-159 */
  31.  0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, /* 160-175 */
  32.  0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, /* 176-191 */
  33.  0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, /* 192-207 */
  34.  0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, /* 208-223 */
  35.  0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, /* 224-239 */
  36.  0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}; /* 240-255 */
      字符'0'~'9'对应的ASCII码为48~57,映射到上面的_ctype数组,相应的位置全是_D,_D&_D则为真,其它的字符则判断为false。对不同种类的字符进行了分类,并使用唯一的二进制来进行标识,使用&和|保证了不同类别的字符不会同时满足两种分类的条件。

阅读(4322) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~