Ale*_*der 3 objective-c type-conversion nsdata
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
Run Code Online (Sandbox Code Playgroud)
现在我如何将数据转换为可以使用的int(即用于执行算术运算)?
由于您正在从文本文件中读取整数,因此可以将其转换为:
char buf[6];
[data getBytes:buf length:5];
buf[5] = '\0';
NSInteger res = atoi(buf);
Run Code Online (Sandbox Code Playgroud)
这假定编码使用每个字符一个字节,这与[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);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1615 次 |
| 最近记录: |