C#实现整型数据字任意编码任意进制的转换和逆转换
又是个闲极无聊的下午,无聊写了这么个东西,可以实现任意整数按照任意编码和任意进制的转换和逆向转换。用途:
恶。。这个我也不清楚,目前看来可以用来做验证码,用来做短网址,其他?暂时没有想到。
上图先:
实现如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
public class Number
{
public string Characters
{
get;
set;
}
public int Length
{
get
{
if (Characters != null)
return Characters.Length;
else
return 0;
}
}
public Number()
{
Characters = "0123456789";
}
public Number(string characters)
{
Characters = characters;
}
/// <summary>
/// 数字转换为指定的进制形式字符串
/// </summary>
/// <param name="number"></param>
/// <returns></returns>
public string ToString(long number)
{
List<string> result = new List<string>();
long t = number;
while (t > 0)
{
var mod = t % Length;
t = Math.Abs(t / Length);
var character = Characters[Convert.ToInt32(mod)].ToString();
result.Insert(0, character);
}
return string.Join("", result.ToArray());
}
/// <summary>
/// 指定字符串转换为指定进制的数字形式
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public long FromString(string str)
{
long result = 0;
int j = 0;
foreach (var ch in new string(str.ToCharArray().Reverse().ToArray()))
{
if (Characters.Contains(ch))
{
result += Characters.IndexOf(ch) * ((long)Math.Pow(Length, j));
j++;
}
}
return result;
}
}
class Program
{
static void Print(long number, Number adapter)
{
Console.WriteLine("输入数字:{0}", number);
Console.WriteLine("规则:{0}\t\t进制:{1}进制", adapter.Characters,adapter.Length);
var numtostr = adapter.ToString(number);
Console.WriteLine("转换结果:{0}", numtostr);
var strtonum = adapter.FromString(numtostr);
Console.WriteLine("逆向转换结果:{0}", strtonum);
Console.WriteLine();
Console.Wr
补充:软件开发 , C# ,