/* * @author Valentin Simonov / http://va.lent.in/ */ using System.Collections.Generic; using System.Text; namespace TouchScript.Utils { /// /// Utility methods to deal with binary data. /// public static class BinaryUtils { /// /// Formats an integer value to a binary string. /// /// The integer value. /// The string builder to use. /// The number of digits to include in the string. public static void ToBinaryString(uint value, StringBuilder builder, int digits = 32) { int i = digits - 1; while (i >= 0) { builder.Append((value & (1 << i)) == 0 ? 0 : 1); i--; } } /// /// Formats an integer value to a binary string. /// /// The integer value. /// The number of digits to include in the string. /// A binary string. public static string ToBinaryString(uint value, int digits = 32) { var sb = new StringBuilder(digits); ToBinaryString(value, sb, digits); return sb.ToString(); } /// /// Converts a collection of bool values to a bit mask. /// /// The collection of bool values. /// Binary mask. public static uint ToBinaryMask(IEnumerable collection) { uint mask = 0; var count = 0; foreach (bool value in collection) { if (value) mask |= (uint) (1 << count); if (++count >= 32) break; } return mask; } } }