NSString *str=@"313233343536";//这是123456的ascii码
怎样把这一段字符串转换成123456呢
NSString *string = [NSString stringWithFormat:@"%c", asciiCode]; //
------解决方案--------------------
- (NSString *)TextFromAsciiCodesString:(NSString *)string
{
NSArray *components = [string componentsSeparatedByString:@" "];
NSUInteger len = [components count];
char new_str[len+1];
int i;
for (i = 0; i < len; ++i)
new_str[i] = [[components objectAtIndex:i] intValue];
new_str[i] = '\0';
return [NSString stringWithCString:new_str
encoding:NSASCIIStringEncoding];
}
转换后输出就是123456
------解决方案--------------------
NSString *str=@"495051525354";
const char* cstr = [str UTF8String];
printf("%s\n", cstr);
char result[strlen(cstr) / 2 + 1];
int resultIdx = 0;
for(int i=0; i<strlen(cstr); i+=2){
char* tmp = malloc(3);
tmp[0] = cstr[i];
tmp[1] = cstr[i+1];
tmp[2] = '\0';
int a = atoi(tmp);
//printf("%d\n", a);
result[resultIdx++] = a;
free(tmp);
}
result[strlen(cstr) / 2] = '\0';
printf("%s\n", result);
你的ASCII码是错的
------解决方案--------------------
NSString *str=@"495051525354";
const char* cstr = [str UTF8String];
printf("%s\n", cstr);
char result[strlen(cstr) / 2 + 1];
int resultIdx = 0;
for(int i=0; i<strlen(cstr); i+=2){
char* tmp = malloc(3);
tmp[0] = cstr[i];
tmp[1] = cstr[i+1];
tmp[2] = '\0';
int a = atoi(tmp);
//printf("%d\n", a);
result[resultIdx++] = a;
free(tmp);