1

I have this function in Java:

private String hexStringToByteString(String s) {

    String r = "";

    for (int i = 0; i < s.length(); i += 2)
        r += (char) Integer.parseInt(s.substring(i, i + 2), 16);   

    return r;
}

and must implement this in Objective C, because I am developing an app and have to do some encryptions. The problem is I don't know how to make the Integer.parseInt part, passing a String and a radix int to the function. Some help will be great.

rmaddy
  • 314,917
  • 42
  • 532
  • 579
André Muniz
  • 708
  • 2
  • 8
  • 17
  • Possible duplicate of http://stackoverflow.com/questions/2501033/nsstring-hex-to-bytes – Rich Apr 12 '14 at 18:03

1 Answers1

0
NSString r = @""; 
r = [r stringByAppendingString: [ [s substringWithRange:NSRangeMake(i, i + 2)] intValue]]; 

Or:

NSMutableString r = @""; 
[r appendingString: [ [s substringWithRange:NSRangeMake(i, i + 2)] intValue]]; 

It's just that I believe there are better ways of achieving the same. Can you provide a bit more about what s contains and what you are about to achieve? e.g. when this is done just to get rid of spaces, then the following would do - even without the for loop.

NSMutableString r = [NSMutableString stringWithString:s];
[r replaceOccurrencesOfString:@" " withString:"" options:NSLiteralSearch range:NSMakeRange(0, [s length])];

Edit in response to your comment. But be warned. Use this as a starting point only. I never did that myself before. There may be better solutions around and it may contain minor mistakes.

- (NSString) hexStringToByteString(NSString s) {

  NSMutableData d = [NSData dataWithLength: [s length] / 2];

  NSUInteger v; 

  for (int i = 0, i < [s length], i+=2) {
    NSScanner *scanner = [NSScanner scannerWithString:[s substringWithRange:NSRangeMake(i, i + 2)]];

    [scanner scanHexInt:&v];

    [d appendBytes:&v length:1];
  }

  NSData r = [[NSString alloc] initWithData:d encoding:NSUTF8StringEncoding];
  return r;
}

You may opt for a different encoding of course.

Hermann Klecker
  • 14,039
  • 5
  • 48
  • 71