Object-C 从字符串中取16进制数到byte数组

来源:互联网 发布:elasticsearch 5.0 sql 编辑:程序博客网 时间:2024/06/10 19:35
  1. //从字符串中取字节数组  
  2. -(NSData*)stringToByte:(NSString*)string  
  3. {  
  4.     NSString *hexString=[[string uppercaseString] stringByReplacingOccurrencesOfString:@" " withString:@""];  
  5.     if ([hexString length]%2!=0) {  
  6.         return nil;  
  7.     }  
  8.     Byte tempbyt[1]={0};  
  9.     NSMutableData* bytes=[NSMutableData data];  
  10.     for(int i=0;i<[hexString length];i++)  
  11.     {  
  12.         unichar hex_char1 = [hexString characterAtIndex:i]; ////两位16进制数中的第一位(高位*16)  
  13.         int int_ch1;  
  14.         if(hex_char1 >= '0' && hex_char1 <='9')  
  15.             int_ch1 = (hex_char1-48)*16;   //// 0 的Ascll - 48  
  16.         else if(hex_char1 >= 'A' && hex_char1 <='F')  
  17.             int_ch1 = (hex_char1-55)*16; //// A 的Ascll - 65  
  18.         else  
  19.             return nil;  
  20.         i++;  
  21.             
  22.         unichar hex_char2 = [hexString characterAtIndex:i]; ///两位16进制数中的第二位(低位)  
  23.         int int_ch2;  
  24.         if(hex_char2 >= '0' && hex_char2 <='9')  
  25.             int_ch2 = (hex_char2-48); //// 0 的Ascll - 48  
  26.         else if(hex_char2 >= 'A' && hex_char2 <='F')  
  27.             int_ch2 = hex_char2-55; //// A 的Ascll - 65  
  28.         else  
  29.             return nil;  
  30.         
  31.         tempbyt[0] = int_ch1+int_ch2;  ///将转化后的数放入Byte数组里  
  32.         [bytes appendBytes:tempbyt length:1];  
  33.     }  
  34.     return bytes;  


原创粉丝点击