3
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(即用于执行算术运算)?

4

5 回答 5

5

由于您正在从文本文件中读取整数,因此可以像这样转换它:

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);
于 2012-12-19T16:23:13.797 回答
2

这样做的一种方法是将数据转换为 NSString 然后从中获取整数值:

// assuming UTF-8 encoding
NSString *temp = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
int val = [temp intValue];

参考文档: NSString

于 2012-12-19T16:25:44.763 回答
2

更一般地说,您可以将其用于货币或科学记数法等,或者用于此处编码的 int 或浮点...

NSString *string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSNumberFormatter * format = [[NSNumberFormatter alloc] init];
[format setNumberStyle:NSNumberFormatterDecimalStyle];
NSNumber * myNumber = [format numberFromString:string];
于 2012-12-19T16:27:11.003 回答
0

如果我这样做,假设 script.txt 包含纯文本,我会使用NSScanner

NSError *error = nil;
NSString *fileString = [NSString stringWithContentsOfFile:scriptPath encoding:NSUTF8StringEncoding error:&error];
if (!fileString) { // Handle error }
NSScanner *scanner = [NSScanner scannerWithString:fileString];
[scanner setScanLocation:i];
int value = 0;
if (![scanner scanInt:&value]) { // Unable to scan integer from string }

// value should contain your integer here
于 2012-12-19T16:29:29.877 回答
0

NSData *dData ;

const char* fData =[dData 字节];

于 2013-12-13T11:44:26.967 回答