Hex与ASCII相互转换函数

来源:互联网 发布:淘宝不能开店了 编辑:程序博客网 时间:2024/05/01 19:54

char  HexToASCII(unsigned char  data_hex)
{
 char  ASCII_Data;
 ASCII_Data=data_hex & 0x0F;
 if(ASCII_Data<10) 
  ASCII_Data=ASCII_Data+0x30; //‘0--9’
 else  
  ASCII_Data=ASCII_Data+0x37;       //‘A--F’
 return ASCII_Data;
}

void HexGroupToString(char *OutStrBuffer, unsigned char *InHexBuffer, unsigned int HexLength)
{
 unsigned int i, k=0;
 for(i=0;i<HexLength;i++)
 {
  OutStrBuffer[k++]=HexToASCII((InHexBuffer[i]>>4)&0x0F);
  OutStrBuffer[k++]=HexToASCII(InHexBuffer[i]&0x0F);
 }
 OutStrBuffer[k]='\0';
}

BOOL StringToHexGroup(unsigned char *OutHexBuffer, char *InStrBuffer, unsigned int strLength)
{
 unsigned int i, k=0;
 unsigned char HByte,LByte;
 if(strLength%2 !=0)
  return FALSE;
 
 for(i=0; i<strLength; i=i+2)
 {
  if(InStrBuffer[i]>='0' && InStrBuffer[i]<='9')
  {
   HByte=InStrBuffer[i]-'0';
  }
  else if(InStrBuffer[i]>='A' && InStrBuffer[i]<='F')
  {
   HByte=InStrBuffer[i]-'A' +10;
  }
  else
  {
   HByte=InStrBuffer[i];
   return FALSE;
  }
  HByte=HByte <<4;
  HByte = HByte & 0xF0;
  if(InStrBuffer[i+1]>='0' && InStrBuffer[i+1]<='9')
  {
   LByte=InStrBuffer[i+1]-'0';
  }
  else if(InStrBuffer[i+1]>='A' && InStrBuffer[i+1]<='F')
  {
   LByte=InStrBuffer[i+1]-'A' +10;
  }
  else
  {
   LByte=InStrBuffer[i];
   return FALSE;
  }
  OutHexBuffer[k++]=HByte |LByte;
 }
 return TRUE;
}

原创粉丝点击