又是個閒極無聊的下午,無聊寫了這麼個東西,可以實現任意整數按照任意編碼和任意進制的轉換和逆向轉換。
用途:
惡。。這個我也不清楚,目前看來可以用來做驗證碼,用來做短網址,其他?暫時沒有想到。
上圖先:
實現如下:
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.WriteLine("============ 無聊的分割線============");
Console.WriteLine();
}
static void Main(string[] args)
{
//傳統的2進制
Number n1 = new Number("01");
//傳統的8進制
Number n2 = new Number("01234567");
//傳統的16進制
Number n3 = new Number("0123456789ABCDEF");
//自定義編碼的N進制,這個可以用來做驗證碼?
Number n4 = new Number("爹媽說名字太長躲在樹後面會被部落發現");
//山寨一個短網址
Number n5 = new Number("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ");
Print(65535, n1);
Print(65535, n2);
Print(65535, n3);
Print(65535, n4);
Print(165535, n5);
Console.ReadKey();
}
}
}
寫完,剛好6點,收拾下班
摘自 林選臣的專欄