- (BOOL)isEncodeGBK:(unichar *)str len:(int)len
{
assert(str);
BOOL isGBK = YES;
BOOL isAllAscii = YES;
for (int i = 0; i < len; i++) {
if (str[i]&0xff80) {
isAllAscii = NO;
if (str[i] > 0x80 && str[i] < 0xFE) {
i++;
} else {
isGBK = NO;
break;
}
}
}
return (!isAllAscii && isGBK);
}
- (NSString *)encodeByGBK
{
uint len = [self length];
NSString *string = nil;
char *s = NULL;
if (len <= 0) {
return nil;
}
unichar *unistr = (unichar *)malloc(len*sizeof(unichar));
if (!unistr) goto _EXIT;
[self getCharacters:unistr];
if (![self isEncodeGBK:unistr len:len]) {
string = [NSString stringWithFormat:@"%@", self];
goto _EXIT;
}
s = (char *)malloc((len+1)*sizeof(unsigned char));
if (!s) goto _EXIT;
//conver short to unsigned char
for (int i = 0; i < len; i++) {
s[i] = unistr[i];
}
s[len]=0;
NSStringEncoding gbkEncoding = CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000);
string = [NSString stringWithCString:(const char *)s encoding:gbkEncoding];
_EXIT:
if (unistr) free(unistr);
if (s) free(s);
return string;
}
{
assert(str);
BOOL isGBK = YES;
BOOL isAllAscii = YES;
for (int i = 0; i < len; i++) {
if (str[i]&0xff80) {
isAllAscii = NO;
if (str[i] > 0x80 && str[i] < 0xFE) {
i++;
} else {
isGBK = NO;
break;
}
}
}
return (!isAllAscii && isGBK);
}
- (NSString *)encodeByGBK
{
uint len = [self length];
NSString *string = nil;
char *s = NULL;
if (len <= 0) {
return nil;
}
unichar *unistr = (unichar *)malloc(len*sizeof(unichar));
if (!unistr) goto _EXIT;
[self getCharacters:unistr];
if (![self isEncodeGBK:unistr len:len]) {
string = [NSString stringWithFormat:@"%@", self];
goto _EXIT;
}
s = (char *)malloc((len+1)*sizeof(unsigned char));
if (!s) goto _EXIT;
//conver short to unsigned char
for (int i = 0; i < len; i++) {
s[i] = unistr[i];
}
s[len]=0;
NSStringEncoding gbkEncoding = CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000);
string = [NSString stringWithCString:(const char *)s encoding:gbkEncoding];
_EXIT:
if (unistr) free(unistr);
if (s) free(s);
return string;
}