xcode 将 NSData 转换为字节数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10696391/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 00:23:12  来源:igfitidea点击:

Convert NSData to byte array

iphoneobjective-ciosxcodensdata

提问by Radix

I want to convert the NSData into byte array and given below is the code that i have used

我想将 NSData 转换为字节数组,下面给出的是我使用的代码

    NSData *imageData = UIImagePNGRepresentation(recipeImage.image);
    NSUInteger len = [imageData length];
    Byte *byteData = (Byte*)malloc(len);
    memcpy(byteData, [imageData bytes], len);
    NSLog(@"%8s",byteData);

But its giving me an error when i post the byteData to the webservice which is given below

但是当我将 byteData 发布到下面给出的网络服务时,它给了我一个错误

"Server was unable to process request. ---> Parameter is not valid."

“服务器无法处理请求。---> 参数无效。”

and when i print the byteData this is what i get in the console

当我打印 byteData 这就是我在控制台中得到的

aPNG

I tried searching the docs for NSData and found the getBytes method but that too was not of any use i was still getting the same error.

我尝试在文档中搜索 NSData 并找到了 getBytes 方法,但这也没有任何用处,我仍然遇到相同的错误。

Could you please let me know from the code above as in where i am wrong or what mistake i am making in converting the data into byte array

您能否从上面的代码中让我知道我错在哪里或者我在将数据转换为字节数组时犯了什么错误

Edit: I have tried using the

编辑:我试过使用

[imageData getBytes:&byteData length:length];

Its giving me a bad access error

它给了我一个错误的访问错误

回答by Parag Bafna

Try this

尝试这个

NSData *imageData = UIImagePNGRepresentation(recipeImage.image);  
NSUInteger len = [imageData length];
Byte *byteData= (Byte*)malloc(len);
[imageData  getBytes:byteData length:len];

回答by gnasher729

Your problem is somewhere totally different.

你的问题在某个地方完全不同。

You are sending data to a web service, and that fails. Show us how you send the data to the web service. Converting NSData to a byte array is absolutely pointless. imageData.bytes is as good a byte array as you are ever going to get.

您正在向 Web 服务发送数据,但失败了。向我们展示您如何将数据发送到网络服务。将 NSData 转换为字节数组是绝对没有意义的。imageData.bytes 是一个和你将要得到的一样好的字节数组。