ANSCII码和BCD码互转

bool AtoBCD(unsigned char* Asc,unsigned char* BCD,int len)
{
int i;
unsigned char ch; //高位
unsigned char cl; //低位
unsigned char temp1;
unsigned char temp2;
unsigned char *Retrun;

Retrun = new unsigned char[len/2+1];

memset(Retrun,0,len/2+1);

for (i=0;i<len/2;i++)
{
temp1 = Asc[2*i]; //高位
temp2 = Asc[2*i+1]; //低位

if ((temp1 >= 'A' && temp1 <= 'F') || (temp1 >='a' && temp1 <= 'f'))
{
ch = (((temp1 -7) & 0x0f)<<4) & 0xff;
}
else if(temp1 >= '0' && temp1 <= '9')
{
ch = ((temp1 & 0x0f)<<4) & 0xff;
}
else
{
return false;
}

//*************************************************************************//

if ((temp2 >= 'A' && temp2 <= 'F') || (temp2 >= 'a' && temp2 <= 'f'))
{
cl = ((temp2 -7) & 0x0f) & 0xff;
}
else if(temp2 >= '0' && temp2 <= '9')
{
cl = (temp2 & 0x0f) & 0xff;
}
else
{
return false;
}

Retrun[i] = ch | cl;
}

memcpy(BCD,Retrun,len/2);
delete []Retrun;

return true;
}

unsigned char *BCDtoA( unsigned char * Data, int Len)
{
int i,j;
unsigned char temp1,temp2;
unsigned char ptr[500];
unsigned char *Ptr;
j=0;

for(i=0;i<Len;i++)
{
temp1=Data[i];
temp2=temp1 & 0x0f ;
if ((temp2>=0x00) && (temp2<=0x09))
{
ptr[i*2+1]=temp2+0x30;
}
else
{
if(temp2==10)
ptr[i*2+1]='A';
else if(temp2==11)
ptr[i*2+1]='B';
else if(temp2==12)
ptr[i*2+1]='C';
else if(temp2==13)
ptr[i*2+1]='D';
else if(temp2==14)
ptr[i*2+1]='E';
else if(temp2==15)
ptr[i*2+1]='F';
}

temp1=Data[i];
temp2=temp1>>4 ;
temp2=temp2 & 0x0f ;

if ((temp2>=0x00) && (temp2<=0x09))
{
ptr[i*2]=temp2+0x30;
}
else
{
if(temp2==10)
ptr[i*2]='A';
else if(temp2==11)
ptr[i*2]='B';
else if(temp2==12)
ptr[i*2]='C';
else if(temp2==13)
ptr[i*2]='D';
else if(temp2==14)
ptr[i*2]='E';
else if(temp2==15)
ptr[i*2]='F';

}
}
Ptr = ptr;
return( Ptr );
}

原文地址:https://www.cnblogs.com/dengpeng1004/p/4713386.html