我是 iPhone 开发的新手,我想将字符串转换为十六进制格式。
例如00A400024F01
,0x00,0xA4,0x00,0x02,0x4F,0x01
我想我应该从分割字符串开始,然后转换分组值。我不知道该怎么做。
你刚刚从这个stackoverflow问题中找到了答案:-
+ (NSString *) stringToHex:(NSString *)str
{
NSUInteger len = [str length];
unichar *chars = malloc(len * sizeof(unichar));
[str getCharacters:chars];
NSMutableString *hexString = [[NSMutableString alloc] init];
for(NSUInteger i = 0; i < len; i++ )
{
// [hexString [NSString stringWithFormat:@"%02x", chars[i]]]; /*previous input*/
[hexString appendFormat:@"%02x", chars[i]]; /*EDITED PER COMMENT BELOW*/
}
free(chars);
return [hexString autorelease];
}
更新
您可以使用以下方法将一根刺分成两根弦:-
NSString * mystring = @"Hello,How are you";// suppos your string like that
NSArray * array = [mystring componentsSeparatedByString:@","];
NSString * str1 = [array objectAtIndex:0]; //Hello
NSString * str2 = [array objectAtIndex:1]; //How are you
如果您想将两个字符串合并为一个字符串,例如:-
NSString *str1=@"hi Sweet Lady";
NSString *str2=@"How are you";
NSString *mainstr=[NSString stringWithFormat:@"%@ %@",str1,str2];
输出是 ==== hi Sweet Lady 你好吗