在xcode中,文件以utf8格式保存。因此,其中变量对象也是以utf8格式保存。不同语言的utf8编码不一样,不同语言的每个字符的utf8编码的字节数不一样,字节码也不一样。
但是英文的utf8编码和ascii码一样,对于英文字符,查看它的ascii码,将字符取出来,就是它的ascii码。
使用英文转换测试,如下所示:
// NSString to ASCII
NSString *string = @"A";
int asciiCode = [string characterAtIndex:0]; // 65
// ASCII to NSString
int asciiCode = 65;
NSString *string = [NSString stringWithFormat:@"%c", asciiCode]; // A
下面两组算法适用于蓝牙,wifi的协议发送
字符串转成ascii字符串:
//字符串转成ascii字符串
+(NSString *)stringToAsci:(NSString *)string {
NSMutableString *mustring = [[NSMutableString alloc]init];
const char *ch = [string cStringUsingEncoding:NSASCIIStringEncoding];
for (int i = 0; i < strlen(ch); i++) {
[mustring appendString:[NSString stringWithFormat:@"%x",ch[i]]];
}
return mustring;
}
字符串转data:
//字符串转成data
+(NSData)hexToBytes:(NSString )dataStr {
NSMutableData data = [NSMutableData data];
int idx;
for (idx = 0; idx+2 <= dataStr.length; idx+=2) {
NSRange range = NSMakeRange(idx, 2);
NSString hexStr = [dataStr substringWithRange:range];
NSScanner* scanner = [NSScanner scannerWithString:hexStr];
unsigned int intValue;
[scanner scanHexInt:&intValue];
[data appendBytes:&intValue length:1];
}
return data;
}
NSData转NSString
NSString *ssid = [[NSString alloc] initWithData:ssidData encoding:NSUTF8StringEncoding];
以下符合NSData转设备Mac地址业务:
//data转String
- (NSString *)convertDataToHexStr:(NSData *)data {
UInt8 bytes[data.length];
[data getBytes:&bytes range:NSMakeRange(0, data.length)];
NSMutableString *hexStr = [NSMutableString string];
for (int i = 0; i < data.length; i++) {
[hexStr appendFormat:@"%02x",bytes[i]];
}
return hexStr;
}
原文链接:https://blog.csdn.net/qq_32117417/java/article/details/95050176
网友评论