一些转换函数

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;
}


其实使用还是比较简单的,根据函数定义及实现即可,需要注意的是,16进制为uchar型,占一个字节,比如0xff,共一个字节,用 hex2str()转换后卫char型,"FF",占两个字节。
       再举个例子,比如我要向串口发送16进制的命令FF EF DD,可以先定义,char *str_send=" FFEFDD"; uchar *buf_hex;
          然后str2hex(buf_hex, 12, str_send);
            write(fdcom, str_send, 6);
              Ok,此过程中,FFEFDD有12字节的char,转换成了需要的6字节的uchar。


上面用的是后来修改过的函数,str2hex();
void str2hex(uchar *hex,int len, char *str)
{
    uchar l4,h4;
    int i,lenstr;
    lenstr = len;
        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;
    }
 
//
void   Str2Hex(char*   str,   char*   hex)   
{   
    int   i=0;   
    int   len   =   strlen(str);   
    char   pTemp[3]={0};   
    for(;i<len;i++)   
    {   
        sprintf(pTemp,"%X",str[i]);   
        strcat(hex,pTemp);   
    }   
}

VC :
//低位在前,高位在后的字节
int ByteToInt(byte B[4])
{
int ans;
ans = ((int)B[0] & 0xff)<<0;
ans +=((int)B[1] & 0xff)<<8;
ans +=((int)B[2] & 0xff)<<16;
ans +=((int)B[3] & 0xff)<<24;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值