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

标签 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(即执行算术运算)?

最佳答案

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

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/

相关文章:

objective-c - 我如何优化这个巨大的 if/else if block 在 observeValueForKey 中

c# - 对象作为接口(interface)

c - warning_cast.c : In function ? fn_print? : warning_cast. c:5:警告:从不同大小的整数转换为指针

ios - 内存泄漏 - NSData 和 NSMutableString

ios - Setter 方法不适用于 UITableViewCell 子类的属性

ios - 定义完成 block 参数列表错误

iPhone CFSocket 传入/传出消息

objective-c - 将整数转换为格式化字符串

ios - 将 NSMutable 字典保存到文档时遇到问题。 UIImage 不会保存/显示

afnetworking - 使用 AFNetwork 上传 NSData 终止我的应用程序