/// <summary> /// Converts the List of bool to a byte array and outputs the number of used bits. /// </summary> /// <param name="self"></param> /// <param name="usedBits"></param> /// <returns></returns> public static int[] ToIntArray(this List <bool> self, out int usedBits) { int[] ret = new int[Mathf.DivideRoundUp(self.Count, 32)]; int byteHeader = 0; int bitHeader = 0; for (usedBits = self.Count - 1; usedBits >= 0; usedBits--) { //last bool is high bit ret[byteHeader] = ret[byteHeader] << 1; if (self[usedBits]) { ret[byteHeader] = ret[byteHeader] | 0x01; } bitHeader++; if (bitHeader >= 32) { byteHeader++; bitHeader = 0; } } usedBits = self.Count; return(ret); }
/// <summary> /// Calculates the 32-bit Flether checksum for the given source bytes. /// </summary> /// <param name="source"></param> /// <returns></returns> public static uint Fletcher32(byte[] source) { if ((source.Length % 2) != 0) { source = source.Append <byte>(0).ToArray(); } ushort[] newSource = new ushort[Mathf.DivideRoundUp(source.Length, 2)]; Buffer.BlockCopy(source, 0, newSource, 0, source.Length); return(Fletcher32(newSource)); }
/// <summary> /// Sends a byte array in a safer way. /// </summary> /// <param name="data">The byte array containing the data to be sent.</param> /// <param name="stream">The stream to send the data to.</param> /// <param name="blockSize">The size of the blocks to be sent.</param> public static void SendToStream(byte[] data, Stream stream, int blockSize) { if (data == null) { throw new ArgumentException("Data must not be null."); } if (data.Length <= 0) { throw new ArgumentException("Data must not be empty."); } if (stream == null) { throw new ArgumentException("Stream must not be null."); } if (!stream.CanWrite) { throw new ArgumentException("Stream must be writeable."); } if (blockSize <= 256) { throw new ArgumentException("Block size must be at least 256 bytes."); } int dataBlockSize = blockSize - headerSize; int remainingBlocks = Mathf.DivideRoundUp(data.Length, dataBlockSize); int head = 0; while (remainingBlocks > 0) { int dataInBlock = Math.Min(data.Length - head, dataBlockSize); //add header containing: block size, remaining blocks and size of data block stream.Write(BitConverter.GetBytes(remainingBlocks), 0, 4); stream.Write(BitConverter.GetBytes(dataInBlock), 0, 4); stream.Write(data, head, dataInBlock); if (remainingBlocks == 0) { byte[] padding = new byte[dataBlockSize - dataInBlock]; Array.Clear(padding, 0, padding.Length); stream.Write(padding, 0, padding.Length); } head += dataInBlock; stream.Flush(); remainingBlocks--; } }