Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determine if UTF-8 encoded NSData contains a null-terminated string

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.

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]];

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


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;
}
like image 290
Sheamus Avatar asked Dec 25 '22 00:12

Sheamus


1 Answers

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
}
like image 170
Tom Harrington Avatar answered Dec 28 '22 08:12

Tom Harrington