// 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 { private static string DIGITS = "0123456789ABCDEF"; private static int FromAny(string s, int radix) { int res = 0; char[] sa = s.ToCharArray(); int sign = 1; for (int i = 0; i < s.Length; i++) { if(sa[i] != '-') { res = res * radix + DIGITS.IndexOf(sa[i]); } else { sign = -1; } } return sign * res; } private static string ToAny(int i, int radix) { if(i >= 0) { string res = ""; int tmp = i; while (tmp > 0) { res = DIGITS.ToCharArray()[tmp % radix] + res; tmp = tmp / radix; } return res; } else { return "-" + ToAny(-i, radix); } } public static int FromDec(string s) { return FromAny(s, 10); } public static string ToDec(int i) { return ToAny(i, 10); } public static int FromHex(string s) { return FromAny(s, 16); } public static string ToHex(int i) { return ToAny(i, 16); } public static int FromBin(string s) { return FromAny(s, 2); } public static string ToBin(int i) { return ToAny(i, 2); } public static void Main(string[] args) { int v = 77; string posstr = ToBin(v); int posnum = FromBin(posstr); Console.WriteLine(posstr + " " + posnum); v = -v; string negstr = ToBin(v); int negnum = FromBin(negstr); Console.WriteLine(negstr + " " + negnum); } } }