C#(进制转换) NumberConversion
封装进制和进制之间的转换(算法)
C# 进制转换(二进制、十六进制、十进制互转)
public class NumberConversion { private static readonly char[] alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".ToCharArray(); public static string Convert(uint baseSystem, uint destinationSystem, string number) => Convert(System.Convert.ToInt32(baseSystem), System.Convert.ToInt32(destinationSystem), number); private static string Convert(int baseSystem, int destinationSystem, string number) { if (baseSystem == 0 || destinationSystem == 0) throw new ArgumentException("Number System connot be zero"); if (number == "0") return "0"; if (baseSystem == destinationSystem) return number.ToString(); long decimalNumber; if (baseSystem != 10) decimalNumber = ConvertToDecimal(baseSystem, number); else decimalNumber = System.Convert.ToInt32(number); if (destinationSystem != 10) return ConvertFromDecimalToAny(decimalNumber, destinationSystem); else return decimalNumber.ToString(); } private static long ConvertToDecimal(int baseSystem, string number) { string numbers = number.ToString(); long[] heavyNumbers = new long[numbers.Length]; int i = 0; int p = numbers.Length - 1; while (i < numbers.Length) { heavyNumbers[i] = System.Convert.ToInt64(Math.Pow(baseSystem, p)) * System.Convert.ToInt64(numbers[i].ToString()); i++; p--; } long decimalNumber = 0; for (int s = 0; s < heavyNumbers.Length; s++) { decimalNumber += heavyNumbers[s]; } return decimalNumber; } private static string ConvertFromDecimalToAny(long decimalNumber, int destinationSystem) { List<long> rest = new List<long>(); while (decimalNumber != 0) { rest.Add(decimalNumber % destinationSystem); decimalNumber = decimalNumber / destinationSystem; } string[] results = new string[rest.Count]; for (int i = 0; i < rest.Count; i++) { if (rest[i] >= 10) { results[i] = alpha[rest[i] - 10].ToString(); } else { results[i] = rest[i].ToString(); } } string result = ""; for (int i = rest.Count - 1; i >= 0; i--) { result += results[i]; } return result; } }
static void Main(string[] args) { //10 进制转 34 进制 Console.WriteLine(NumberConversion.Convert(10, 34, "19366")); }
在进行进制数直接转换时,`ToString`、`ToInt32`中要转换成的进制数参数要明确,大多是转成几进制,就直接在参数中填写几进制(其中二进制转十进制、二进制转16进制除外)。
二进制(字符串)转换为十进制的结果为32位有符号整数,转换进数为2;
二进制(字符串)转换为十六进制的结果为整型,为了将其表示成十六进制,还需要借助`string.Format("{0:x}", 转换的二进制数)`将其表示为十六进制,转换进数为2;
十进制(整型)转二进制的结果为字符串,转换进数为2;
十进制(整型)转十六进制的结果为字符串,转换进数为16;
十六进制(整型)转二进制的结果为字符串,转换进数为2;
十六进制(整型)转十进制的结果为字符串,转换进数为10。
总的来说,在进行进制转换时,二进制必须为字符串作为转换参数。