数据转换-整数字节数组
utils.h
#ifndef UTILS_H
#define UTILS_H
int Int2ByteArr(unsigned int i, unsigned char * ba);
int ByteArr2Int(unsigned char * ba,unsigned int * i);
#endif
test.c
#include<stdio.h>
#include"utils.h"
int main(){
unsigned int i=20191315;
unsigned char ba [100];
Int2ByteArr(i, ba);
printf("ba=%s\n",ba);
unsigned char bb [] = "75DDFA16";
unsigned int h;
ByteArr2Int(bb, &h);
printf("%d\n",h);
}
u.c
#include<stdio.h>
#include"utils.h"
#include<string.h>
int Hex2Char(int f,char *t)
{
if(f>=0&&f<=9)
{
*t= f+'0';
}
else if(f>=10&&f<=15)
{
*t = f+'A'-10;
}
else
{
printf("input error!");
}
}
int Char2Hex(char f,int *t1)
{
if(f>='0'&& f<='9')
{
*t1= f-'0';
}
else if(f>='A'&& f<='F')
{
*t1= f-'A'+10;
}
else
{
printf("input error!");
}
}
int Int2ByteArr(unsigned int i, unsigned 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(unsigned char * ba,unsigned int * i)
{
int len;
int j;
int n=0;
*i=0;
len = strlen(ba);
for(j=0;j<len;j++)
{
Char2Hex(ba[j],&n);
*i=(*i)*16+n;
}
}