namespace ImageProcessor { using System; internal static class ByteExtensions { /// /// Converts a byte array to a new array where each value in the original array is represented /// by a the specified number of bits. /// /// The bytes to convert from. Cannot be null. /// The number of bits per value. /// The resulting array. Is never null. /// is null. /// is less than or equals than zero. public static byte[] ToArrayByBitsLength(this byte[] bytes, int bits) { Guard.NotNull(bytes, "bytes"); Guard.GreaterThan(bits, 0, "bits"); byte[] result; if (bits < 8) { result = new byte[bytes.Length * 8 / bits]; int factor = (int)Math.Pow(2, bits) - 1; int mask = 0xFF >> (8 - bits); int resultOffset = 0; foreach (byte b in bytes) { for (int shift = 0; shift < 8; shift += bits) { int colorIndex = ((b >> (8 - bits - shift)) & mask) * (255 / factor); result[resultOffset] = (byte)colorIndex; resultOffset++; } } } else { result = bytes; } return result; } } }