Search code examples
cocoaasciinsmutablestringstringwithformat

NSMutableString stringWithFormat


I have java code that prepares a message for a MD5 munge

private static char[] jimsCopyRight = {

'C', 'o', 'p', 'y', 'r', 'i', 'g', 'h', 't', ':', ' ', 0xa9, ' '};

which is used in

StringBuffer message = new StringBuffer();

message.append(name.toLowerCase()); message.append(new String(jimsCopyRight));

When I print out the message using

for(int i = 0; i < message.length(); i++){

System.out.println(" i = " + i + " char " + message.substring(i, i + 1) + " charAT " + message.charAt(i)); }

I get i = 14 char \251 charAT \251 and the message.toString is jimCopyright: \251

I need to construct a NSMutableString with the same characters.

Among the things I have tried

wDevCopyright = [NSString stringWithFormat:@"jimCopyright: %c ", 0xa9];
for(int i = 0; i < [message length]; i++){
  NSLog(@"i = %d char %c %d", i, [message characterAtIndex:i], [message characterAtIndex:i]);
 }

Which gives me i = 14 char © 169

Any help in getting the NSMutableString to be the same as the StringBuffer will be appreciated.


The problem is that when I munge the two strings in MD5 I get different results when I add the 0xa9. The prints are just for getting a look at the strings.

I'm thinking it has something to do with the char[] in Java and the construct of the NSMutableString. I do not believe they are the same values.

I have some C code and it declares the copyright as

#define jimsCopyRight  "Copyright: � "

The Java MD5 and C MD5 of the copyright are the same.


Solution

  • The copyright symbol is what you wanted, right? According to your question, that's what you got. So what's the problem?

    (This is why magic numbers are bad. I can't tell from your code alone what encoding's 0xa9 you wanted.)

    If you're wondering why it says 169 instead of 251, it's because Java prints out the octal (base-8) character escape sequence, whereas %d in the C standard library, Core Foundation, and Foundation prints out the value as decimal (base-10). \251 is not the two hundred and fifty-first character. Use %o to print the value as octal, or %x to print it as hexadecimal (base-16). Or, use Calculator.app's Programming mode to convert 251 from octal to decimal.

    BTW, you can use the %@ format sequence and the NSUserName function to insert your username into the string, just like you did in the Java code. No need to hard-code it.