将NSString编码为CP1252 / windows1252

时间:2014-06-02 14:29:57

标签: objective-c nsstring encode

所有

我有一个NSString,其字符为UTF8格式。我想将其解码为CP1252 / Windows-1252格式。 采取的行动:
- 将NSString转换为字节数组(UTF8-decode)
- 将字节数组编码为CP1252 / windows1252格式的字节数组
- 从字节数组中读取第一个元素

我该怎么做?我已经阅读了很多关于CFstring的文档,但我不明白。

我做了什么:

    NSString *tileData = @"4¬";

NSNumber *value = [NSNumber numberWithInt:[[tileData substringWithRange:NSMakeRange(0, 1)] intValue]];
NSString *pos = [tileData substringWithRange:NSMakeRange(1, 1)];


// first attempt: create byte-array from NSString into UTF8. Then create NSString in CP1252 format.
    NSData *data = [pos dataUsingEncoding:NSUTF8StringEncoding]; 
    NSLog(@"Data =%@",data);
    NSString *htmlSTR = [[NSString alloc] initWithData:data
                                              encoding:NSWindowsCP1252StringEncoding]; 
    NSLog(@"htmlSTR =%@", htmlSTR);
    NSData *data2 = [htmlSTR dataUsingEncoding:NSWindowsCP1252StringEncoding];
    NSLog(@"Data2 =%@",data2);


// second attempt: create byte-array from NSString into CP1252. Then create NSString in CP1252 format.
    NSData *data11 = [pos dataUsingEncoding:NSWindowsCP1252StringEncoding];
    NSLog(@"Data11 =%@",data11);
    NSString *htmlSTR2 = [[NSString alloc] initWithData:data11
                                              encoding:NSWindowsCP1252StringEncoding]; 
    NSLog(@"htmlSTR2 =%@", htmlSTR2);
    NSData *data21 = [htmlSTR2 dataUsingEncoding:NSWindowsCP1252StringEncoding];
    NSLog(@"Data21 =%@",data21);

希望有人可以帮助我或有一个例子。

1 个答案:

答案 0 :(得分:0)

解决方案:

NSString *tileData = @"4æ";
NSNumber *value = [NSNumber numberWithInt:[[tileData substringWithRange:NSMakeRange(0, 1)] intValue]];
NSString *pos = [tileData substringWithRange:NSMakeRange(1, 1)];

int position = [tileData  characterAtIndex:1];

if (position > 128) {

    NSData *data = [pos dataUsingEncoding:NSUTF8StringEncoding];
    NSString *htmlSTR = [[NSString alloc] initWithData:data
                                              encoding:NSWindowsCP1252StringEncoding];
    NSData *data2 = [htmlSTR dataUsingEncoding:NSWindowsCP1252StringEncoding];

    uint8_t *bytes = (uint8_t *)[data2 bytes];
    NSMutableString *posstring = [NSMutableString stringWithCapacity:3];
    [posstring appendFormat:@"%d", bytes[1]];
    NSNumber *posgroot;
    posgroot = [NSNumber numberWithInt:[posstring intValue]];
    position = [posstring intValue];
    if (position <0) position +=256;
}

奇怪的是UTF8和ASCII之间的区别: http://www.utf8-chartable.de/unicode-utf8-table.pl?utf8=dechttp://www.asciitable.com

另外,我不确定最好的解决方案是使用NSData的编码,然后编码为NSString,再次编码为NSDATA。

但这现在有效!