Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert byte[] to Point[] and back

Tags:

c#

xamarin

Is it possible to convert byte[] to Point? I have a canvas and the drawing obtained as Point[]; I need to store it in the database as byte[] and then retrieve it and load it again as Point[].


1 Answers

You can serialize your points into a binary stream to get an array of bytes:

byte[] data;
using (var ms = new MemoryStream()) {
    using (var bw = new BinaryWriter(ms)) {
        bw.Write(points.Length);
        foreach (var p in points) {
            bw.Write(p.X);
            bw.Write(p.Y);
        }
    }
    data = ms.ToArray();
}

To deserialize your bytes back into an array, reverse the process:

Point[] points;
using (var ms = new MemoryStream(data)) {
    using (var r = new BinaryReader(ms)) {
        int len = r.ReadInt32();
        points = new Point[len];
        for (int i = 0 ; i != len ; i++) {
            points[i] = new Point(r.ReadInt32(), r.ReadInt32());
        }
    }
}
like image 146
Sergey Kalinichenko Avatar answered Jun 05 '26 23:06

Sergey Kalinichenko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!