public static class BaseConversion
{
// 将字符串从一种进制转换为另一种进制
public static string ConvertBase(string number, int fromBase, int toBase)
{
if (fromBase == toBase)
return number;
// 将字符串从原始进制转换为十进制整数
int decimalNumber = Convert.ToInt32(number, fromBase);
// 将十进制整数转换为目标进制的字符串
return Convert.ToString(decimalNumber, toBase);
}
// 将字节数组转换为指定进制的字符串
public static string BytesToBaseString(byte[] bytes, int baseNumber)
{
StringBuilder sb = new StringBuilder();
foreach (byte b in bytes)
{
sb.Append(Convert.ToString(b, baseNumber));
}
return sb.ToString();
}
// 将指定进制的字符串转换为字节数组
public static byte[] BaseStringToBytes(string baseString, int baseNumber)
{
int byteLength = (int)Math.Ceiling((double)baseString.Length / 2);
byte[] bytes = new byte[byteLength];
for (int i = 0; i < byteLength; i++)
{
int startIndex = i * 2;
int endIndex = startIndex + 2;
if (endIndex > baseString.Length)
endIndex = baseString.Length;
string byteString = baseString.Substring(startIndex, endIndex - startIndex);
bytes[i] = (byte)Convert.ToInt32(byteString, baseNumber);
}
return bytes;
}
}
注:
1.ConvertBase 方法接受一个字符串表示的数字、原始进制和目标进制,然后返回转换后的字符串。
2.BytesToBaseString 方法接受一个字节数组和目标进制,然后返回一个表示这些字节的字符串,其中每个字节都转换为了指定的进制。
3.BaseStringToBytes 方法接受一个表示字节的字符串和进制,然后返回一个字节数组,其中每个字节都是从字符串中解析出来的。