如何将文本中的16进制数据转换为2进制数组
如何将文本中的16进制数据转换为2进制数组
root@~ #cat stob.c #include <stdio.h> #include <string.h> int main (void) { char str[10],*p=str; int a[32],i=0,j=1,k,sum=0,l=0,*s=a; //input hex string printf("Enter a Hex-string:"); gets(p); //point to the right of character p=str+strlen(p)-1; //From character to integer,Result in Sum. while(*p) { if(*p>='0'&&*p<='9') { sum+=(*p-'0')*j; } else if(*p>='a'&&*p<='f') { sum+=(*p-'a'+10)*j; } else { printf("Input Error! Exit!\n"); return -1; } j*=16; p--; } //Convert to binary array,Reslut in a[] do { a[i]=sum%2; sum/=2; i++; }while(sum!=0); //Reverse array j=i-1; for(k=0;k<=j/2;k++,j--) { sum=a[k]; a[k]=a[j]; a[j]=sum; } //Display binary array printf("%s's binary is : ",str); while(l<i) printf("%i",*(s+l++)); printf("\n"); return 0; } 测试: root@~ #./stob Enter a Hex-string:f f's binary is : 1111 root@~ #./stob Enter a Hex-string:1234abcd 1234abcd's binary is : 10010001100101010011111001101 root@~ #./stob Enter a Hex-string:sdf4 Input Error! Exit! root@~ #./stob Enter a Hex-string:ffff ffff's binary is : 1111111111111111 root@~ #