How to use NULL character with NSString?

前端 未结 5 1034
梦毁少年i
梦毁少年i 2021-01-19 05:12

In PHP, I can call base64_encode(\"\\x00\". $username. \"\\x00\". $password) and the \"\\x00\" represents a NULL character.

Now, in Objecti

5条回答
  •  -上瘾入骨i
    2021-01-19 05:30

    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 
    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).

提交回复
热议问题