BCD与字符串相互转换

时间:2022-06-06 17:53:08
BCD与字符串相互转换BCD与字符串相互转换View Code
 1  bool  BCDtoStr( char   * str,unsigned  char   * BCD, int  BCD_length)
 2  {
 3       if (BCD == 0   ||  BCD_length == 0 )
 4           return   false ;
 5       int  i,j;
 6       for (i = 0 ,j = 0 ;i < BCD_length;i ++ ,j += 2 )
 7      {
 8          str[j] =  (BCD[i] >> 4 >   9   ?  (BCD[i] >> 4 ) - 10 + ' A '  : (BCD[i] >> 4 ) + ' 0 ' ;
 9          str[j + 1 ] = (BCD[i]  &   0x0F > 9   ?  (BCD[i]  &   0x0F ) - 10 + ' A '  : (BCD[i]  &   0x0F ) + ' 0 ' ;
10      }
11      str[j] = ' \0 ' ;
12       return   true ;
13  }
14  bool  StrtoBCD( char   * str,unsigned  char   * BCD, int   * BCD_length)
15  {
16       if (str == 0 return   false ;
17       int  tmp = strlen(str);
18      tmp -= tmp % 2 ;
19       if (tmp == 0 return   false ;
20       int  i,j;
21       for (i = 0 ;i < tmp;i ++ )
22      {
23           if (str == 0   ||
24               ! (str[i] >= ' 0 '   &&  str[i] <= ' 9 '   ||  str[i] >= ' a '   &&  str[i] <= ' f '   ||  str[i] >= ' A '   &&  str[i] <= ' F ' )
25              )
26               return   false ;
27      }
28      
29       for (i = 0 ,j = 0 ;i < tmp / 2 ;i ++ ,j += 2 )
30      {
31          str[j] > ' 9 '   ?  
32              (str[j] > ' F '   ?  BCD[i] = str[j] - ' a ' + 10  : BCD[i] = str[j] - ' A ' + 10 )
33              : BCD[i] = str[j] - ' 0 ' ;
34          str[j + 1 ] > ' 9 '   ?  
35              (str[j + 1 ] > ' F '   ?  BCD[i] = (BCD[i] << 4 ) + str[j + 1 ] - ' a ' + 10  : BCD[i] = (BCD[i] << 4 ) + str[j + 1 ] - ' A ' + 10 )
36              : BCD[i] = (BCD[i] << 4 ) + str[j + 1 ] - ' 0 ' ;        
37      }
38       if (BCD_length)
39           * BCD_length = tmp / 2 ;
40       return   true ;    
41  }