Objective C 各种数据类型转换笔记大全

这个笔记,是为了让自己想不起的时候随时可以回顾一下,我不会说是因为自己懒不想记的 ·。·

以后会一直添加工作学习期间遇见的类型转换在这里~~

欢迎收录查阅~~~

ASCII码互转NSString

ASCII码表

//1.ASCII码转NSString
unichar ch =65;
NSString *str =[NSString stringWithUTF8String:(char *)&ch];
//-->A

// ASCII to NSString

int asciiCode = 65;
NSString *string = [NSString stringWithFormat:@"%c", asciiCode]; // A
//-->A


//2.NSString转ASCII码
NSString *string = @"]";
int asciiCode = [string characterAtIndex:0];
//-->93

NSString 互转 char*

//NSString转char
//方法一
NSString *t = @"字符串";
const char *t2 =[t UTF8String];

//方法二
NSString * cocoaString = @"My NSString";
const char * myCstring = [cocoaString cStringUsingEncoding:NSUTF8StringEncoding];

//方法三
NSString *t = @"字符串1";
char mychar[100];
strcpy(mychar,(char *)[t UTF8String]);

//Char转NSString
//方法一
NSString * cocoaString = [[NSString alloc] initWithCString:mychar encoding:NSUTF8StringEncoding];

//方法二
const char * cString = "Hello";
NSString *TempString =[NSString stringWithFormat:@"%s",cString];

//方法三
const char * cString = "Hello";
NSString *str=[NSString stringWithCString:cString encoding:NSUTF8StringEncoding];

NSData 互转 char*

//Char*转NSData
//方法一
char * postData = "TEST";
NSData *data = [NSData dataWithBytes:postData length:strlen(postData)];
//方法二 先转NSString再转data

//NSData转Char*
[data bytes];

NSString 互转 NSData

//NSString转NSData
NSData *data =[str dataUsingEncoding:NSUTF8StringEncoding];

//NSData转NSString
NSString * str  =[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];

NSDictionary互转NSData

//dic转data
NSData *datax= [NSJSONSerialization dataWithJSONObject:jsonDic options:NSJSONWritingPrettyPrinted error:nil];
//data转dic
NSDictionary *dictionary =[NSJSONSerialization JSONObjectWithData:datax options:NSJSONReadingMutableLeaves error:nil];

十六进制转十进制

//    十六进制格式字符串(带不带0x都可)转成数字
unsigned int outVal;
NSScanner* scanner = [NSScanner scannerWithString:@"0x83"];
[scanner scanHexInt:&outVal];
NSLog(@"%d", outVal);
//-->131

十六进制转NSString

NSString * str = @"68656C6C6F";
NSMutableString * newString = [[NSMutableString alloc] init] ;
int i = 0;
while (i < [str length])
{
    NSString * hexChar = [str substringWithRange: NSMakeRange(i, 2)];
    int value = 0;
    sscanf([hexChar cStringUsingEncoding:NSASCIIStringEncoding], "%x", &value);
    [newString appendFormat:@"%c", (char)value];
    i+=2;
}
NSLog(@"new str :%@",newString); 
//-->new str :hello

NSString互转NSNumber

//NSString转NSNumber
//方法一
NSString * str = @"890909";
// 字符串转为NSInteger类型
NSInteger num = [str integerValue];
// 字符串转为NSNumber对象类型
NSNumber * nums = @(num);
//方法二,简化写法
NSNumber * nums = @([str integerValue]);

//NSNumber转NSString
NSNumberFormatter *number = [[NSNumberFormatter alloc] init];
NSString *b = [number stringFromNumber:nums];

Objective C Char *,Const Char *,Cstring,CFString互转

Mark:之前的笔记,现在挪到这边。

-1. NSString转cstring

NSString *string1 = @"i am NSString";
NSLog(@"To cString : %s",[string1 UTF8String]);

-2. Const Char,Char转NSString

const char *cString = "i am const CString";
char *cString2 = "I am char";
NSLog(@"TO NSString1: %@",[NSString stringWithUTF8String:cString]);
NSLog(@"TO NSString2: %@",[NSString stringWithUTF8String:cString2]);

-3. Const Char 转Char

char* 表示一个指针变量,并且这个变量是可以被改变的。

const char*表示一个限定不会被改变的指针变量(意思是指针指向的内容不可变,但指针本身可以再赋值)

//方法一 strdup
//strdup()在内部调用了malloc()为变量分配内存,不需要使用返回的字符串时,需要用free()释放相应的内存空间
const char *cString = "i am const CString";
char *string2 = strdup(cString);
NSLog(@"To char1: %s",string2);
free(string2);
NSLog(@"To char2: %s",string2);

//方法二:强转const char
char *string3 = (char *)cString;
NSLog(@"To char3: %s",string3);
        

-4. Char 转Const Char

//强转
char *string4 = "I am Char";
const char *cString  = string4;
NSLog(@"To const char:%s",cString);

-5. NSString 互转CFString

NSString *aNSString = @"NSString";
CFStringRef aCFString = (__bridge CFStringRef)aNSString;
NSString *bNSString = (__bridge NSString *)aCFString;
NSLog(@"the CFString : %@",aCFString);
NSLog(@"the NSString : %@",bNSString);

-6. Char 转CFString

char *cStringA = "cStringA";
CFStringRef bCFString =CFStringCreateWithCString(NULL, cStringA, kCFStringEncodingUTF8);
NSLog(@"the cfString : %@",bCFString);

-7. CFString转Char

第一种:利用CF 内置方法拿到String

//方法一 通过ssize_t
        ssize_t s = CFStringGetMaximumSizeForEncoding(CFStringGetLength(bCFString), kCFStringEncodingUTF8);
        char *d = malloc(s);
        if(d) {
            CFStringGetCString(bCFString, d, s, kCFStringEncodingUTF8);
            printf("%s\n", d);
            free(d);
        }
//方法二 通过CFIndex
CFIndex length = CFStringGetLength(bCFString);
          CFIndex maxSize = CFStringGetMaximumSizeForEncoding(length, kCFStringEncodingUTF8) + 1;
          char *buffer = (char *)malloc(maxSize);
          if (CFStringGetCString(bCFString, buffer, maxSize,
                                 kCFStringEncodingUTF8)) {
              printf("%s\n", buffer);
          }

第二种:利用前面的关系将CFstring转成NSString再转成char

NSString *testNS = (__bridge NSString *)bCFString;
char *testC =(char *) [testNS UTF8String];
NSLog(@"-->%s",testC);

[Objective C 十六进制 十进制互转]

Mark:之前的笔记,现在挪到这边。

十六进制转十进制:

NSString *hexStr = @"0xff";
UInt64 mac1 =  strtoul([hexStr UTF8String], 0, 16);
NSLog(@"%llu",mac1);
NSLog(@"十六进制转十进制 --->%lu",strtoul(hexStr.UTF8String, 0, 16));

如果有溢出的话,使用scanner:

NSString *hexStr1 = @"0x00000000027743330000000000714C9C";
unsigned long long result = 0;
NSScanner *scanner = [NSScanner scannerWithString:hexStr1];
[scanner scanHexLongLong:&result];
NSLog(@"%llu",result);

十六进制转NSString

 NSString * str = @"68656C6C6F";
    NSMutableString * newString = [[NSMutableString alloc] init] ;
    int i = 0;
    while (i < [str length])
    {
        NSString * hexChar = [str substringWithRange: NSMakeRange(i, 2)];
        int value = 0;
        sscanf([hexChar cStringUsingEncoding:NSASCIIStringEncoding], "%x", &value);
        [newString appendFormat:@"%c", (char)value];
        i+=2;
    }
    NSLog(@"new str :%@",newString); 
//-->new str :hello

十进制转十六进制:

NSLog(@"十进制转十六进制 --->%@",[NSString stringWithFormat:@"%x",255]);

或者:

+(NSString *)ToHex:(long long int)tmpid
{
    NSString *nLetterValue;
    NSString *str =@"";
    long long int ttmpig;
    for (int i = 0; i<9; i++) {
        ttmpig=tmpid%16;
        tmpid=tmpid/16;
        switch (ttmpig)
        {
            case 10:
                nLetterValue =@"A";break;
            case 11:
                nLetterValue =@"B";break;
            case 12:
                nLetterValue =@"C";break;
            case 13:
                nLetterValue =@"D";break;
            case 14:
                nLetterValue =@"E";break;
            case 15:
                nLetterValue =@"F";break;
            default:nLetterValue=[[NSString alloc]initWithFormat:@"%lli",ttmpig];
                
        }
        str = [nLetterValue stringByAppendingString:str];
        if (tmpid == 0) {
            break;
        }     
    }
    return str;
}
上一篇:iOS 开发面试通关指南:67 个必知问题!


下一篇:结构体和类的区别-Objective-C基础