欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

C-switch case之如何巧妙判断范围区域

程序员文章站 2022-07-02 17:28:45
当判断整数时 示例: 判断整数范围 打印: 当判断字符时 示例: 将"0x00"~"0xff"转化为数值0x00~0xff 打印: ......

当判断整数时

  • 示例: 判断整数范围
#include <stdio.h>

int main()
{    
    unsigned char buf[6]={0x00,0x07,0x11,0x60,0x61,0x66};
    
    for(int i=0;i<6;i++)
    switch(buf[i])
    {
        case 0x00 ... 0x10: printf("buf[%d] is 0x0 ~0x10\n",i);  break;
        case 0x11 ... 0x20: printf("buf[%d] is 0x11~0x20\n",i);  break;
        case 0x30 ... 0x60: printf("buf[%d] is 0x30~0x60\n",i);  break;
        case 0x61 ... 0xff: printf("buf[%d] is 0x61~0xff\n",i);  break;
    } 
} 

打印:

C-switch case之如何巧妙判断范围区域

 

当判断字符时

  • 示例: 将"0x00"~"0xff"转化为数值0x00~0xff
#include <stdio.h>


int main()
{    
    char buf[6][6]={"0xff","0x02","0x1f","0xf1","0xa1","0xb0"};
for(int i=0;i<6;i++) if(buf[i][0]=='0'&&(buf[i][1]=='x' || buf[i][1]=='x')) //匹配前缀 { unsigned char val=0; int err=0; for(int j=2;j<4;j++) switch(buf[i][j]) { case '0' ... '9' : val= val*16 + (buf[i][j]-'0'); break; case 'a' ... 'f' : val= val*16 + (buf[i][j]-'a'+10); break; case 'a' ... 'f' : val= val*16 + (buf[i][j]-'a'+10); break; default : err =1; break; }
if(!err) printf("buf[%d] = 0x%02x\n",i,val); else printf("buf[%d] err \n",i); } else printf("buf[%d] err \n",i); }

打印:

C-switch case之如何巧妙判断范围区域