string chars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
private void button1_Click(object sender, EventArgs e)
{
int i = int.Parse(textBox1.Text);
textBox2.Text = EncodeNum(i);
textBox3.Text = DecodeNum(textBox2.Text).ToString();
}
/// <summary>
/// 转码
/// </summary>
/// <param name="integer"></param>
/// <returns></returns>
private string EncodeNum(int integer)
{
double number = integer;
int hex = chars.Length;
StringBuilder sb = new StringBuilder();
do
{
//计算指数
int exp = -1;
double value = 0;
while (value < number)
{
exp++;
value = Math.Pow(hex, exp + 1);
}
//计算对应字符
double num = number / Math.Pow(hex, exp);
int index = Convert.ToInt32(Math.Floor(num));
sb.Append(chars.Substring(index, 1));
number = number % Math.Pow(hex, exp);
} while (number > 0);
return sb.ToString();
}
/// <summary>
/// 解码
/// </summary>
/// <param name="s"></param>
/// <returns></returns>
private int DecodeNum(string s)
{
double x = 0;
int hex = chars.Length;
for (int i = 0; i < s.Length; i++)
{
int exp = s.Length - 1 - i;
int num = chars.IndexOf(s.Substring(i, 1));
x += num * Math.Pow(hex, exp);
}
return Convert.ToInt32(x);
}
private void button1_Click(object sender, EventArgs e)
{
int i = int.Parse(textBox1.Text);
textBox2.Text = EncodeNum(i);
textBox3.Text = DecodeNum(textBox2.Text).ToString();
}
/// <summary>
/// 转码
/// </summary>
/// <param name="integer"></param>
/// <returns></returns>
private string EncodeNum(int integer)
{
double number = integer;
int hex = chars.Length;
StringBuilder sb = new StringBuilder();
do
{
//计算指数
int exp = -1;
double value = 0;
while (value < number)
{
exp++;
value = Math.Pow(hex, exp + 1);
}
//计算对应字符
double num = number / Math.Pow(hex, exp);
int index = Convert.ToInt32(Math.Floor(num));
sb.Append(chars.Substring(index, 1));
number = number % Math.Pow(hex, exp);
} while (number > 0);
return sb.ToString();
}
/// <summary>
/// 解码
/// </summary>
/// <param name="s"></param>
/// <returns></returns>
private int DecodeNum(string s)
{
double x = 0;
int hex = chars.Length;
for (int i = 0; i < s.Length; i++)
{
int exp = s.Length - 1 - i;
int num = chars.IndexOf(s.Substring(i, 1));
x += num * Math.Pow(hex, exp);
}
return Convert.ToInt32(x);
}