Skip to content

Instantly share code, notes, and snippets.

@poychang
Last active August 18, 2022 09:00
Show Gist options
  • Save poychang/3c21c48e5eaff3d2dd39cbb30c0ee753 to your computer and use it in GitHub Desktop.
Save poychang/3c21c48e5eaff3d2dd39cbb30c0ee753 to your computer and use it in GitHub Desktop.
[10 進制數轉換成 62 進制] #dotnet
void Main()
{
Converter.FromDecimalTo62Hex(10).Dump();
Converter.From62HexToDecimal("a").Dump();
Converter.FromDecimalTo62Hex(100).Dump();
Converter.From62HexToDecimal("1C").Dump();
}
// Define other methods and classes here
public static class Converter
{
// 62 進位編碼,可加一些字符也可以實現 72, 96 等任意進制轉換,但是有符號數據不直觀,會影響閱讀
private static String keys = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
private static int carrying = keys.Length; // 進位數(62 進位)
/// <summary>
/// 10 進制數轉換成 62 進制
/// </summary>
/// <param name="value">10 進制的數字,最大值為 decimal.MaxValue</param>
/// <returns>回傳從 10 進制數字轉換成 62 進制的文字</returns>
public static string FromDecimalTo62Hex(decimal value)
{
string result = string.Empty;
do
{
decimal index = value % carrying;
result = $"{keys[(int)index]}{result}";
value = (value - index) / carrying;
}
while (value > 0);
return result;
}
/// <summary>
/// 62 進制數轉換成 10 進制數
/// </summary>
/// <param name="value">62 進制的文字</param>
/// <returns>回傳從 62 進制文字轉換成 10 進制的數字</returns>
public static decimal From62HexToDecimal(string value)
{
decimal result = 0;
for (int i = 0; i < value.Length; i++)
{
int x = value.Length - i - 1;
result += keys.IndexOf(value[i]) * Pow(carrying, x);
}
return result;
}
/// <summary>
/// Decimal 數值的 N 次方
/// </summary>
/// <param name="baseNumber">基底數值</param>
/// <param name="exponentail">次方</param>
/// <returns></returns>
private static decimal Pow(decimal baseNumber, decimal exponentail)
{
decimal value = 1; // 任何數的 0 次方,結果都等於 1
while (exponentail > 0)
{
value = value * baseNumber;
exponentail--;
}
return value;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment