1. 程式人生 > >char[]->NSString;char[]->NSData;十六進位制和普通字串互轉;NSString轉為utf16格式char[]

char[]->NSString;char[]->NSData;十六進位制和普通字串互轉;NSString轉為utf16格式char[]

char[]->NSSrting

  char name[32];
  NSString *str = [NSString stringWithUTF8String:name];
  char name[1008] = 接收到的char陣列  //陣列大小改為自己的
  Byte byte[1008];
  memcpy(byte, name,1008);
  NSString *str = [[NSString alloc]initWithBytes:byte length:1008 encoding:NSUTF16StringEncoding];

NSString 轉為 UTF16格式char[]

  NSString *name = "我最帥";
  char sname[24];
  NSData *data = [name dataUsingEncoding:NSUTF16StringEncoding];
  Byte byte [data.length];
  memcpy(byte, [data bytes],sizeof(byte));
  memcpy(sname,byte , sizeof(byte));

char[]->NSData

  UInt8 data[1008];
  NSData *sdata = [NSData dataWithBytesNoCopy:data length:1008 freeWhenDone:NO]; //不用
  freeWhenDone的話裡面轉的時候有時會主動斷開報錯

將NSString轉換成十六進位制的字串

+ (NSString *)convertStringToHexStr:(NSString *)str {
    if (!str || [str length] == 0) {
        return @"";
    }
//    NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding];
    NSData *data = [str dataUsingEncoding:NSUTF16BigEndianStringEncoding];

    
    NSMutableString *string = [[NSMutableString alloc] initWithCapacity:[data length]];
    
    [data enumerateByteRangesUsingBlock:^(const void *bytes, NSRange byteRange, BOOL *stop) {
        unsigned char *dataBytes = (unsigned char*)bytes;
        for (NSInteger i = 0; i < byteRange.length; i++) {
            NSString *hexStr = [NSString stringWithFormat:@"%x", (dataBytes[i]) & 0xff];
            if ([hexStr length] == 2) {
                [string appendString:hexStr];
            } else {
                [string appendFormat:@"0%@", hexStr];
            }
        }
    }];
    
    return string;
}

將十六進位制的字串轉換成NSString

+ (NSString *)convertHexStrToString:(NSString *)str
{
    if (!str || [str length] == 0)
    {
        return nil;
    }
    
    NSMutableData *hexData = [[NSMutableData alloc] initWithCapacity:8];
    NSRange range;
    if ([str length] % 2 == 0)
    {
        range = NSMakeRange(0, 2);
    }
    else
    {
        range = NSMakeRange(0, 1);
    }
    for (NSInteger i = range.location; i < [str length]; i += 2)
    {
        unsigned int anInt;
        NSString *hexCharStr = [str substringWithRange:range];
        
        NSLog(@"hexCharStr:%@",hexCharStr);
        
        NSScanner *scanner = [[NSScanner alloc] initWithString:hexCharStr];
        
        [scanner scanHexInt:&anInt];
        NSData *entity = [[NSData alloc] initWithBytes:&anInt length:1];
        [hexData appendData:entity];
        
        range.location += range.length;
        range.length = 2;
    }
    
    NSString *string = [[NSString alloc]initWithData:hexData encoding:NSUTF8StringEncoding];
    return string;
}