开发者

How to go from NSData to byte[]

If I have image data in an NSData, extracted from the开发者_如何学Go image as follows, how do I convert this NSData object into a byte array?

NSData data = NSData.FromUrl(NSUrl.FromString(urlString));


NSData data = NSData.FromUrl(NSUrl.FromString(urlString));

byte[] dataBytes = new byte[data.Length];

System.Runtime.InteropServices.Marshal.Copy(data.Bytes, dataBytes, 0, Convert.ToInt32(data.Length));


I got an answer to this question from the reply by Dimitris Tavlikos to this question I asked:

How to read the contents of a local image into a base64 string in MonoTouch

From that answer I learnt that if you include a reference System.Linq then the NSData object will have a ToArray() method that will return an array of bytes. So with this namespace referenced you can do the following:

bytes[] dataBytes = data.ToArray();

Hope this info helps someone else.


Timo's answer as an extension method:

    public static byte[] ToByteArray (this NSData data) {
        var dataBytes = new byte[data.Length];
        System.Runtime.InteropServices.Marshal.Copy(data.Bytes, dataBytes, 0, Convert.ToInt32(data.Length));
        return dataBytes;
    }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜