How to use NULL character with NSString?

前端 未结 5 1036
梦毁少年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条回答
  •  不知归路
    2021-01-19 05:34

    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 alloc] initWithBytes:bytes length:sizeof(bytes) encoding:NSUTF8StringEncoding];
    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.

提交回复
热议问题