把Mac地址字符串转换为占一个字节的十六进制数
把Mac地址字符串转换为占一个字节的十六进制数(用指针函数返回值)
#include <stdio.h> #include <stdlib.h> #include <string.h> unsigned char *getMac() { char n[6][5]; char mac[20]="80:32:C0:AF:55:AB"; sscanf(mac,"%[^:]:%[^:]:%[^:]:%[^:]:%[^:]:%[^:]",n[0],n[1],n[2],n[3],n[4],n[5]); int i, j; int m[2]; static unsigned char data[6]={0}; //需要定义成静态变量,避免随函数周期结束而收回达不到传递返回值的效果。静态变量定义后不会随着函数生命周期结束,而是进程生命周期结束而结束(相对于全局变量) for(i=0;i<6;i++) { for(j=0;j<2;j++) { if(n[i][j]=='0') m[j]=0; else if(n[i][j]=='1') m[j]=1; else if(n[i][j]=='2') m[j]=2; else if(n[i][j]=='3') m[j]=3; else if(n[i][j]=='4') m[j]=4; else if(n[i][j]=='5') m[j]=5; else if(n[i][j]=='6') m[j]=6; else if(n[i][j]=='7') m[j]=7; else if(n[i][j]=='8') m[j]=8; else if(n[i][j]=='9') m[j]=9; else if((n[i][j]=='a') || (n[i][j]=='A')) m[j]=10; else if((n[i][j]=='b') || (n[i][j]=='B')) m[j]=11; else if((n[i][j]=='c') || (n[i][j]=='C')) m[j]=12; else if((n[i][j]=='d') || (n[i][j]=='D')) m[j]=13; else if((n[i][j]=='e') || (n[i][j]=='E')) m[j]=14; else if((n[i][j]=='f') || (n[i][j]=='F')) m[j]=15; printf("m[%d]=%d\n",j,m[j]); } data[i] = m[0]<<4 | m[1]; }
printf("0x%x\n0x%x\n0x%x\n0x%x\n0x%x\n0x%x\n",data[0],data[1],data[2],data[3],data[4],data[5]); return data; } int main() { unsigned char *str = getMac(); printf("0x%x\t0x%x\t0x%x\t0x%x\t0x%x\t0x%x\n",str[0],str[1],str[2],str[3],str[4],str[5]); return 0; }
把Mac地址字符串转换为占一个字节的十六进制数(地址参)
#include <stdio.h> #include <stdlib.h> #include <string.h> void getMac(unsigned char *data) { char n[6][2]; char mac[20]="80:32:C0:AF:55:AB"; sscanf(mac,"%[^:]:%[^:]:%[^:]:%[^:]:%[^:]:%[^:]",n[0],n[1],n[2],n[3],n[4],n[5]); int i, j; int m[2]; for(i=0;i<6;i++) { for(j=0;j<2;j++) { if(n[i][j]=='0') m[j]=0; else if(n[i][j]=='1') m[j]=1; else if(n[i][j]=='2') m[j]=2; else if(n[i][j]=='3') m[j]=3; else if(n[i][j]=='4') m[j]=4; else if(n[i][j]=='5') m[j]=5; else if(n[i][j]=='6') m[j]=6; else if(n[i][j]=='7') m[j]=7; else if(n[i][j]=='8') m[j]=8; else if(n[i][j]=='9') m[j]=9; else if((n[i][j]=='a') || (n[i][j]=='A')) m[j]=10; else if((n[i][j]=='b') || (n[i][j]=='B')) m[j]=11; else if((n[i][j]=='c') || (n[i][j]=='C')) m[j]=12; else if((n[i][j]=='d') || (n[i][j]=='D')) m[j]=13; else if((n[i][j]=='e') || (n[i][j]=='E')) m[j]=14; else if((n[i][j]=='f') || (n[i][j]=='F')) m[j]=15; } *(data+i) = m[0]<<4 | m[1]; }
printf("0x%x\t0x%x\t0x%x\t0x%x\t0x%x\t0x%x\n",*data,*(data+1),*(data+2),*(data+3),*(data+4),*(data+5)); } int main() { unsigned char data[10]; getMac(data); printf("0x%x\t0x%x\t0x%x\t0x%x\t0x%x\t0x%x\n",data[0],data[1],data[2],data[3],data[4],data[5]); return 0; }