0

In Java code, this code can get hex string "efbfbc";

new String((((char)-4 )+ "").getBytes("utf8"),"iso8859-1")

How can implement it in iOS Objective-C?

by byte -4, get hex string "efbfbc";

dbcock
  • 1
  • 3
  • 1
    Possible duplicate of [Convert UTF-8 encoding to ISO 8859-1 encoding with NSString](https://stackoverflow.com/questions/4553388/convert-utf-8-encoding-to-iso-8859-1-encoding-with-nsstring) – Jorge Barrios Jul 11 '17 at 04:02
  • In UTF-8, bytes `EF BF BC` are Unicode codepoint U+FFFC. `(char)-4` is hex `0xFFFC`, so why not use `0xFFFC` instead of `-4` so it is easier to read? In any case, [there are many ways to create a hex string for a byte array](https://stackoverflow.com/questions/9655181/). I wouldn't use ISO-8859-1 for that, especially since [many bytes are not defined in it](https://en.wikipedia.org/wiki/ISO/IEC_8859-1), so you may end up with `'?'` chars at times, or even an exception: "*The behavior of this constructor when the given bytes are not valid in the given charset is unspecified*". – Remy Lebeau Jul 12 '17 at 22:15
  • For iOS, see [How to convert an NSString to hex values](https://stackoverflow.com/questions/3056757/) and [How can i convert NSdata to hex string?](https://stackoverflow.com/questions/16521164/). – Remy Lebeau Jul 12 '17 at 22:21

2 Answers2

0
NSString *string = @"efbfbc";
char converted[([string length] + 1)];
NSString* str = [[NSString alloc]
                 initWithCString: converted encoding: NSISOLatin1StringEncoding];

NSLog(@"Your result string: %@",str);

I got below result:

enter image description here

Check out this AppleDoc for more information about intiWithCString method. It will give you a clear idea.

Nirmalsinh Rathod
  • 5,079
  • 4
  • 26
  • 56
  • How is this supposed to work? `converted` is an empty `char` array. – rmaddy Jul 11 '17 at 04:26
  • It will get input from your string which you need to make convert. – Nirmalsinh Rathod Jul 11 '17 at 04:27
  • Huh? How is `converted` populated in your code (hint: it's not). – rmaddy Jul 11 '17 at 04:28
  • Your code is incorrect. You are passing an initialized `char` array into the `initWithCString` method. You never populate `converted` with any characters. The screen grab you posted shows `str` containing random garbage data because of this problem. – rmaddy Jul 11 '17 at 04:39
0

i have solve the problem.

unichar asciiChar = -4;
NSString *string  = [NSString stringWithCharacters:&asciiChar length:1];
 string = [NSString stringWithCString:[string UTF8String] encoding: NSISOLatin1StringEncoding];

now , string hex is "efbfbc"

thanks everyone.

dbcock
  • 1
  • 3