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
现在我该如何将数据转换为我可以使用的 int(即执行算术运算)?
最佳答案
由于您是从文本文件中读取整数,因此可以像这样转换它:
char buf[6];
[data getBytes:buf length:5];
buf[5] = '\0';
NSInteger res = atoi(buf);
这假设一个编码每个字符使用一个字节,这与您提供的代码片段中的 [file readDataOfLength: 5]
调用一致。
如果事先不知道位数,您可以这样做:
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);
关于Objective-C:将 NSData 转换为 int 或 char,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13956580/