确定UTF-8编码的NSData是否包含以空字符结尾的字符串 [英] Determine if UTF-8 encoded NSData contains a null-terminated string

查看:89
本文介绍了确定UTF-8编码的NSData是否包含以空字符结尾的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 NSData 类别中进行了从NSData到NSString的转换,因为我一直在使用 NSString 方法: initWithData:encoding:.但是,根据这个答案 https://stackoverflow.com/a/2467856/1231948 ,这不是那么简单

I have the NSData-to-NSString conversion in an NSData Category, because I'm always using the NSString method: initWithData:encoding:. But, according to this answer, https://stackoverflow.com/a/2467856/1231948, it is not that simple.

到目前为止,我在 NSData 类别中拥有此方法,以与其他从相同名称的方法返回字符串的数据对象中的方法保持一致:

So far, I have this method in my NSData Category, in an effort to keep consistent with methods in other data objects that return a string from a method with the same name:

- (NSString *) stringValue
{
    return [[NSString alloc] initWithData:self encoding:NSUTF8StringEncoding];
}

到目前为止,它是成功的,但是我想确定一个字符串是否为空终止,以决定是否应该使用此方法,也可以从答案链接中进行

So far it is successful, but I would like to determine if a string is null-terminated, to decide whether I should use this method instead, also from the answer link:

NSString* str = [NSString stringWithUTF8String:[data bytes]];

如何确定UTF-8编码的 NSData 是否包含以空值结尾的字符串?

How do I determine if UTF-8 encoded NSData contains a null-terminated string?

在获得下面的答案之后,我为 NSData 类别方法 stringValue 编写了更详尽的实现:

After getting the answer below, I wrote more thorough implementation for my NSData Category method, stringValue:

- (NSString *) stringValue
{
    //Determine if string is null-terminated
    char lastByte;
    [self getBytes:&lastByte range:NSMakeRange([self length]-1, 1)];

    NSString *str;

    if (lastByte == 0x0) {
        //string is null-terminated
        str = [NSString stringWithUTF8String:[self bytes]];
    } else {
        //string is not null-terminated
        str = [[NSString alloc] initWithData:self encoding:NSUTF8StringEncoding];
    }

    return str;
}

推荐答案

空终止从字面上意味着最后一个字节的值为零.很容易检查:

Null termination literally means that the last byte has a value of zero. It's easy to check for:

char lastByte;
[myNSData getBytes:&lastByte range:NSMakeRange([myNSData length]-1, 1)];
if (lastByte == 0x0) {
    // string is null terminated
} else {
    // string is not null terminated
}

这篇关于确定UTF-8编码的NSData是否包含以空字符结尾的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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