如何使用NULL字符与NSString? [英] How to use NULL character with NSString?

查看:102
本文介绍了如何使用NULL字符与NSString?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在PHP中,我可以调用 base64_encode(\x00。$ username。\x00。$ password) \ x00表示一个空字符。

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

现在,在Objective-C中,我有一个函数将NSData转换为由DaveDribin创建的base64编码的NSString

Now, in Objective-C, I have a function that converts NSData to base64 encoded NSString created by DaveDribin.

我如何从具有NULL个字符的字符串创建数据?

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

这似乎不起作用...

This doesn't seem to work...

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


推荐答案

像这样:

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

NSLog(@"%@", data);

输出:

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

或从 NSString

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

您可以在开头,用户名/密码和结尾之间看到空字节 char [] 为空终止。

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

这篇关于如何使用NULL字符与NSString?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆