using System;
using System.Collections.Generic;
namespace Base62
{
internal class Program
{
static void Main(string[] args)
{
var oldKey = 366767374860158M;
var res = Decimal2Str(oldKey);
Console.WriteLine(res);
var jiemi = Str2Decimal(res);
Console.WriteLine(jiemi);
Console.ReadKey();
}
private static readonly string Keys = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ~!@#$%^&*()_=-+<>/\\[]{};?.,";//编码,可加一些字符也可以实现72,96等任意进制转换,但是有符号数据不直观,会影响阅读。
private static readonly int Exponent = Keys.Length;//幂数
/// <summary>
/// decimal 转N进制
/// </summary>
/// <param name="val"></param>
/// <returns></returns>
public static string Decimal2Str(decimal val)
{
Stack<char> rr = new Stack<char>();
do
{
decimal ys = val % Exponent;
val /= Exponent;
rr.Push(Keys[(int)ys]);
if (val < Exponent)
{
rr.Push(Keys[(int)val]);
}
} while (val >= Exponent);
var str = string.Empty;
while (rr.Count > 0)
{
str += rr.Pop();
}
return str;
}
/// <summary>
/// N进制字符串转decimal
/// </summary>
/// <param name="value">62 encode string</param>
/// <returns>Return a specified decimal number that decode by 62 string</returns>
public static decimal Str2Decimal(string value)//bUI6zOLZTrj
{
decimal result = 0;
for (int i = 0; i < value.Length; i++)
{
int x = value.Length - i - 1;
result += Keys.IndexOf(value[i]) * Pow(Exponent, x);// Math.Pow(exponent, x);
}
return result;
}
/// <summary>
/// 一个数据的N次方
/// </summary>
/// <param name="x"></param>
/// <returns></returns>
private static decimal Pow(decimal baseNo, decimal x)
{
decimal value = 1;1 will be the result for any number's power 0.任何数的0次方,结果都等于1
while (x > 0)
{
value = value * baseNo;
x--;
}
return value;
}
}
}
C# 短链思路如何将长id转化为短的
猜你喜欢
转载自blog.csdn.net/qq_36437991/article/details/131358922
今日推荐
周排行