views:

342

answers:

4

In php i can call base64_encode("\x00". $username. "\x00". $password) and the "\x00" represents a NULL character.

I have a function that converts NSData to base64 encoded NSString created by DaveDribin.

How do I create data from a string that has null characters?

This doesnt seem to work...

NSData * authCode = [[NSString stringWithFormat:@"%c%@%c%@", '\0', self.username, '\0', self.password] dataUsingEncoding:NSUTF8StringEncoding];
A: 

Not quite sure why this works, but instead of using @"%c" as the format string with '\0', try using @"%@" as the format string with @"\0"

RJ
+1  A: 

Your syntax is correct. NSString just doesn't handle NULL bytes well. I can't find any documentation about it, but NSString will silently ignore %c format specifiers with an argument of 0 (and on that note, the character constant '\0' expands to the integer 0; that is correct). It can, however, handle \0 directly embedded into an NSString literal.

See this code:

#import <Cocoa/Cocoa.h>
int main (int argc, char const *argv[])
{
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    NSString *stringByChars = [NSString stringWithFormat:@"-%c%c%c%c-",0,0,0,0];
    NSString *stringByEscapes = [NSString stringWithFormat:@"-\0\0\0\0-"];
    NSLog(@"  stringByChars: \"%@\"", stringByChars);
    NSLog(@"            len: %d", [stringByChars length]);
    NSLog(@"           data: %@", [stringByChars dataUsingEncoding:NSUTF8StringEncoding]);
    NSLog(@"stringByEscapes: \"%@\"", stringByEscapes);
    NSLog(@"            len: %d", [stringByEscapes length]);
    NSLog(@"           data: %@", [stringByEscapes dataUsingEncoding:NSUTF8StringEncoding]);
    [pool drain];
    return 0;
}

returns:

  stringByChars: "--"
            len: 2
           data: <2d2d>
stringByEscapes: "-
            len: 6
           data: <2d000000 002d>

(Note that since the stringByEscapes actually contains the NULL bytes, it terminates the NSLog string early).

Matt B.
+1  A: 

Like this:

char bytes[] = "\0username\0password";
NSData * data = [NSData dataWithBytes:bytes length:sizeof(bytes)];

NSLog(@"%@", data);

Output:

2010-01-22 09:15:22.546 app[6443] <00757365 726e616d 65007061 7373776f 726400>

Or from NSString:

char bytes[] = "\0username\0password";
NSString * string = [NSString string];
[string initWithBytes:bytes length:sizeof(bytes)];
NSData * data = [string dataUsingEncoding:NSUTF8StringEncoding];

You can see the null bytes at the beginning, in between username/password and at the end - because the char[] is null terminated.

stefanB
A: 

stefanB looks like a right option. Turns out I was passing in wrong info to make it look like \0 wasnt working

[NSString stringWithFormat:@"\0user\0pass"] this was ok.

Thanks all

joels