5

how can I have this conversion from NSWindowsCP1251StringEncoding to UTF-8? I had several attempts but no one worked as it should. My last try was:

NSData *dt = [mystr dataUsingEncoding:NSUTF8StringEncoding];
NSString *str = [NSString alloc] initWithData:dt encoding:NSWindowsCP1251StringEncoding];

The result of str is unreadable. Did anyone encounter anything similar?

skolima
  • 31,963
  • 27
  • 115
  • 151
Bill
  • 51
  • 1
  • 2
  • 1
    How do you obtain the CP1251 string in the first place? –  Feb 09 '11 at 08:52
  • In your code example, you first convert `mystr` from whatever it is to UTF-8, then you create a new string, but tell `NSString` that it's CP1251. Which is supposed to be CP1251? – 一二三 Feb 09 '11 at 08:56
  • @Bavarious : The string comes from socket connection. – Bill Feb 09 '11 at 09:13
  • @Phil : So how I create an NSString from my converted UTF8 data?? – Bill Feb 09 '11 at 09:14
  • When you call initWithData:encoding:, tell `NSString` that it's `NSUTF8StringEncoding`... – 一二三 Feb 09 '11 at 09:21
  • In that way I get the same string as before conversion.. – Bill Feb 09 '11 at 09:38
  • Given the sequence of bytes you get from the socket, send `-[NSString initWithBytes:length:encoding]` or `-[NSString initWithData:encoding:]`, passing `NSWindowsCP1251StringEncoding` as the encoding. –  Feb 09 '11 at 18:04

1 Answers1

7

I think you were so close:

// Convert it back to CP1251
NSData *dt = [mystr dataUsingEncoding:NSWindowsCP1251StringEncoding];

// Now load it as UTF8
NSString *str = [NSString alloc] initWithData:dt encoding:NSUTF8StringEncoding];
Tom van der Woerdt
  • 29,532
  • 7
  • 72
  • 105
  • The last one is wrong: Encoding must be the encoding of the data, so NSWindowsCP1251StringEncoding. You should add that an NSString itself doesn't have an encoding (in practice). – gnasher729 Oct 15 '14 at 09:05