ios 如何从 NSData 读取字节
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12453078/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to read bytes from NSData
提问by Deepak Pillai
Can anyone suggest a method to read bytes from NSData
(like read function in @interface
NSInputStream
: NSStream
)
任何人都可以提出来读取字节的方法NSData
(如在读功能@interface
NSInputStream
:NSStream
)
采纳答案by Martin R
You can also create an NSInputStream
from an NSData
object, if you need the read interface:
如果您需要读取接口,您还可以NSInputStream
从NSData
对象创建一个:
NSData *data = ...;
NSInputStream *readData = [[NSInputStream alloc] initWithData:data];
[readData open];
However, you should be aware that initWithData
copiesthe contents of data.
但是,您应该知道initWithData
复制数据的内容。
回答by Pravitha V
"How to read binary bytes in NSData?" may help you:
“如何读取 NSData 中的二进制字节?”可能对您有帮助:
NSString *path = @"…put the path to your file here…";
NSData * fileData = [NSData dataWithContentsOfFile: path];
const char* fileBytes = (const char*)[fileData bytes];
NSUInteger length = [fileData length];
NSUInteger index;
for (index = 0; index<length; index++)
{
char aByte = fileBytes[index];
//Do something with each byte
}
回答by Alex Rablau
One of the simplest ways is to use NSData getBytes:range:.
最简单的方法之一是使用NSData getBytes:range:。
NSData *data = ...;
char buffer[numberOfBytes];
[data getBytes:buffer range:NSMakeRange(position, numberOfBytes)];
where position and length is the position you want to read from in NSData and the length is how many bytes you want to read. No need to copy.
其中 position 和 length 是您要在 NSData 中读取的位置,length 是您要读取的字节数。无需复制。
回答by Jevgenij Kononov
May way of doing that.. do not forget to free byte array after usage.
可能的方式..不要忘记在使用后释放字节数组。
NSData* dat = //your code
NSLog(@"Receive from Peripheral: %@",dat);
NSUInteger len = [dat length];
Byte *bytedata = (Byte*)malloc(len);
[dat getBytes:bytedata length:len];
int p = 0;
while(p < len)
{
printf("%02x",bytedata[p]);
if(p!=len-1)
{
printf("-");
}//printf("%c",bytedata[p]);
p++;
}
printf("\n");
// byte array manipulation
free(bytedata);
回答by Dimitar Nestorov
Alex already mentionedNSData getBytes:range: but there is also NSData getBytes:length:which starts from the first byte.
Alex已经提到了NSData getBytes:range: 但还有NSData getBytes:length:从第一个字节开始。
NSData *data = ...;
char buffer[numberOfBytes];
[data getBytes:buffer range:numberOfBytes];