一些比较好用的16进制与字符,asc之间的转换程序

void hex2str(char *str, uchar *hex,int len)
{
 int i;
 uchar l4,h4;
 for(i=0; i<len; i++) {
  h4=(hex[i] & 0xf0)>>4;
  l4=hex[i] & 0x0f;
  if (h4<=9) 
   str[2*i] = h4 + ('0' -0);
  else
   str[2*i] = h4 + ('A'-10);
  
  if (l4<=9) 
   str[2*i+1] = l4 + ('0' -0);
  else
   str[2*i+1] = l4 + ('A'-10);
 }
 str[2*i]=0;
}
uchar asc2hex(char asccode)
{
 uchar ret;
 if('0'<=asccode && asccode<='9')
  ret=asccode-'0';
 else if('a'<=asccode && asccode<='f')
  ret=asccode-'a'+10;
 else if('A'<=asccode && asccode<='F')
  ret=asccode-'A'+10;
 else
  ret=0;
 return ret;
}
void ascs2hex(uchar *hex,uchar *ascs,int srclen)
{
 uchar l4,h4;
 int i,lenstr;
 lenstr = srclen;
 if(lenstr==0){
  return;
 }
 if(lenstr%2)
  return;
 for(i=0; i<lenstr; i+=2){
  h4=asc2hex(ascs[i]);
  l4=asc2hex(ascs[i+1]);
  hex[i/2]=(h4<<4)+l4;
 }
}
void str2hex(uchar *hex, int *len, char *str)
{
 uchar l4,h4;
 int i,lenstr;
 lenstr = strlen(str);
 if(lenstr==0){
  *len = 0;
  return;
 }
 for(i=0; i<lenstr-(lenstr%2); i+=2){
  h4=asc2hex(str[i]);
  l4=asc2hex(str[i+1]);
  hex[i/2]=(h4<<4)+l4;
 }
 if(lenstr%2)
  hex[(lenstr+1)/2-1]=asc2hex(str[lenstr-1]) << 4;
 *len=(lenstr+1)/2;
}
posted @ 2014-04-16 14:13  Zucc_zt  阅读(879)  评论(0编辑  收藏  举报