将字符串转换为二进制data类型

//将字符串转换成data

  • (NSData)dataForHexString:(NSString)hexString{
    if (hexString == nil) {
    return nil;
    }
    const char* ch = [[hexString lowercaseString] cStringUsingEncoding:NSUTF8StringEncoding];
    NSMutableData* data = [NSMutableData data];

    while (ch) {
    if (
    ch == ' ') {
    continue;
    }
    char byte = 0;

      if ('0' <= *ch && *ch <= '9') {
          byte = *ch - '0';
      }
      else if ('a' <= *ch && *ch <= 'f') {
          
          byte = *ch - 'a' + 10;
      }
      else if ('A' <= *ch && *ch <= 'F') {
          
          byte = *ch - 'A' + 10;
      }
      ch++;
      byte = byte << 4;
      
      if (*ch) {
          
          if ('0' <= *ch && *ch <= '9') {
              
              byte += *ch - '0';
              
          } else if ('a' <= *ch && *ch <= 'f') {
              
              byte += *ch - 'a' + 10;
          }
          else if('A' <= *ch && *ch <= 'F')
          {
              byte += *ch - 'A' + 10;
          }
          ch++;
      }
      [data appendBytes:&byte length:1];
    

    }
    return data;

}

你可能感兴趣的:(将字符串转换为二进制data类型)