Objective-C:将NSData转换为int或char

时间:2012-12-19 16:18:02

标签: 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

现在我如何将数据转换为可以使用的int(即用于执行算术运算)?

5 个答案:

答案 0 :(得分: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);

答案 1 :(得分:2)

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

NSString *string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSNumberFormatter * format = [[NSNumberFormatter alloc] init];
[format setNumberStyle:NSNumberFormatterDecimalStyle];
NSNumber * myNumber = [format numberFromString:string];

答案 2 :(得分:1)

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

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

参考文件: NSString

答案 3 :(得分: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

答案 4 :(得分:0)

NSData * dData;

const char * fData = [dData bytes];