Search code examples
objective-ctype-conversionnsdata

Objective-C: Converting NSData to an int or char


NSData * data;
NSFileHandle * file;

file = [NSFileHandle fileHandleForReadingAtPath: @"script.txt"]; //this is wrong, as I have to provide a full pathname, but disregard for now

[file seekToFileOffset: i]; //i not mentioned here, as this is only a snippet of code. Suffice to know that in the file it falls at the beginning of an integer I want to read

data = [file readDataOfLength: 5]; //5-digit integer that I want to read

Now how do I go about casting data as an int which I can use (i.e. for performing arithmetic operations)?


Solution

  • Since you are reading your integer from a text file, you can convert it like this:

    char buf[6];
    [data getBytes:buf length:5];
    buf[5] = '\0';
    NSInteger res = atoi(buf);
    

    This assumes an encoding that uses one byte per character, which is consistent with the call of [file readDataOfLength: 5] in the code snippet that you provided.

    If the number of digits is not known ahead of time, you can do this:

    char buf[11]; // Max 10 digits in a 32-bit number + 1 for null terminator
    bzero(buf, 11);
    [data getBytes:buf length:variableLength];
    NSInteger res = atoi(buf);