iPhone写入二进制数据 [英] iPhone writing binary data
本文介绍了iPhone写入二进制数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
你怎么写二进制数据到一个文件?我想写花车到一个文件中,原,然后读取回为浮动。你是怎么做到的?
How do you write binary data to a file? I want to write floats to a file, raw, and then read them back as floats. How do you do that?
推荐答案
被这个实验:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *file = [documentsDirectory stringByAppendingPathComponent:@"binaryData"];
float b = 32.0f;
NSMutableData *data = [NSMutableData dataWithLength:sizeof(float)];
[data appendBytes:&b length:sizeof(float)];
[data writeToFile:file atomically:YES];
NSData *read = [NSData dataWithContentsOfFile:file];
float b2;
NSRange test = {0,4};
[read getBytes:&b2 range:test];
奇怪的是,写入的文件似乎是8个字节,而不是4甚至可以用0长度初始化NSData的,追加一个浮动,然后写,然后该文件将4个字节。为什么NSData的默认添加4个字节?长度为4 NSData的一应导致文件长度为4,而不是8。
The weird thing is that the file written seems to be 8 bytes and not 4. It is even possible to init the nsdata with 0 length, append a float and then write, and then the file will be 4 bytes. Why is NSData adding 4 bytes by default? A NSData with length 4 should result in a file with length 4, not 8.
这篇关于iPhone写入二进制数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文