Advertisement
Ajes

serialize / deserialize 2d bool array

May 6th, 2015
525
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.39 KB | None | 0 0
  1. public static byte[] SerializeMap(bool[,] map) {
  2.  
  3.             byte[] arr = new byte[map.Length + 8];
  4.             byte[] widthBytes = BitConverter.GetBytes(map.GetLength(0));
  5.             byte[] heigthBytes = BitConverter.GetBytes(map.GetLength(1));
  6.             arr[0] = widthBytes[0];
  7.             arr[1] = widthBytes[1];
  8.             arr[2] = widthBytes[2];
  9.             arr[3] = widthBytes[3];
  10.             arr[4] = heigthBytes[0];
  11.             arr[5] = heigthBytes[1];
  12.             arr[6] = heigthBytes[2];
  13.             arr[7] = heigthBytes[3];
  14.  
  15.             int position = 8;
  16.  
  17.             for (int x = 0; x < map.GetLength(0); x++) {
  18.                 for (int y = 0; y < map.GetLength(1); y++) {
  19.                     arr[position] = BitConverter.GetBytes(map[x, y])[0];
  20.                     position++;
  21.                 }
  22.             }
  23.  
  24.             return arr;
  25.  
  26.         }
  27.  
  28.         public static bool[,] DeserializeMap(byte[] arr) {
  29.  
  30.             int width = BitConverter.ToInt32(arr, 0);
  31.             int heigth = BitConverter.ToInt32(arr, 4);
  32.             bool[,] map = new bool[width, heigth];
  33.             int position = 8;
  34.  
  35.             for (int x = 0; x < width; x++) {
  36.                 for (int y = 0; y < heigth; y++) {
  37.                     map[x, y] = BitConverter.ToBoolean(arr, position);
  38.                     position++;
  39.                 }
  40.             }
  41.             return map;
  42.  
  43.         }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement