数据转换-整数字节数组
代码
main.c
#include<stdio.h> #include"utils.h" int main(){ int p; char bytearr[100]; printf("please input\n"); scanf("%d",&p); printf("change int to char\n"); INT2ByteArr(p,bytearr); printf("char%s\n",bytearr); char barr[100]; int h; printf("please input char:"); scanf("%s",barr); printf("change char to int:"); ByteArr2INT(barr,&h); printf("%d\n",h); }
utils.c
#include<stdio.h> #include"utils.h" #include<string.h> int Hex2Char(int fromi,char *toc) { if(fromi>=0&&fromi<=9) { *toc= fromi+'0'; } else if(fromi>=10&&fromi<=15) { *toc = fromi+'A'-10; } else { printf("incorrect!"); } return 0; } int Char2Hex(char fromc,int *toi) { if(fromc>='0'&& fromc<='9') { *toi= fromc-'0'; } else if(fromc>='A'&& fromc<='F') { *toi= fromc-'A'+10; } else { printf("incorrect"); } return 0; } int INT2ByteArr(int i,char *ba){ int j; int a; int sum=0; int k=i; for(j=0;;j++) { k=k/16; if(k!=0) sum++; else break; } for(j=sum;j>=0;j--){ a = i%16; Hex2Char(a,&ba[j]); i=i/16; } ba[sum+1]='\0'; } int ByteArr2INT(char *ba,int *i) { int len; int j; int n=0; *i=0; len = strlen(ba); for(j=0;j<len;j++) { Char2Hex(ba[j],&n); //printf("%d\n",n); *i=(*i)*16+n; } }
运行截图