// Collection of code snippets by Arne Vajhøj // (likely posted to comp.os.vms/INFO-VAX, INFO-TPU, MACRO32, eksperten.dk, newz.dk, LinkedIn or other place sometime between 1990 and now) using System; namespace E { public class Program { public static int Test1(String s) { int j, k, m = 0; int len = s.Length - 1; for (int i = 0; i <= len; i++) { j = 1; k = (s[i] - '0'); if ((k > 1) || (k < 0)) { throw new System.IO.InvalidDataException("Invalid input. Must be 0 or 1"); } j = j << (len - i); m = m + k * j; } return m; } public static int Test2(String s) { int result = 0; foreach (char c in s) { if (c != '0' && c != '1') { throw new ArgumentException("Invalid input. Must be 0 or 1."); } result <<= 1; result += c & 1; } return result; } public static int Test3(String s) { int result = 0; foreach (char c in s) { result <<= 1; if (c == '1') { result += 1; } else if (c != '0') { throw new ArgumentException("Invalid input. Must be 0 or 1."); } } return result; } private const int N = 100000000; private const string S = "1010101001100110"; public static void Main(string[] args) { Console.WriteLine(Test1(S)); DateTime dt1 = DateTime.Now; for(int i = 0; i < N; i++) { Test1(S); } DateTime dt2 = DateTime.Now; Console.WriteLine("Original: " + (dt2 - dt1).TotalSeconds); Console.WriteLine(Test2(S)); DateTime dt3 = DateTime.Now; for(int i = 0; i < N; i++) { Test2(S); } DateTime dt4 = DateTime.Now; Console.WriteLine("Goeran: " + (dt4 - dt3).TotalSeconds); Console.WriteLine(Test3(S)); DateTime dt5 = DateTime.Now; for(int i = 0; i < N; i++) { Test3(S); } DateTime dt6 = DateTime.Now; Console.WriteLine("Peter: " + (dt6 - dt5).TotalSeconds); } } }