using System;
|
using System.Collections.Generic;
|
using System.Linq;
|
|
namespace Link.Common
|
{
|
/// <summary>
|
/// 地址工具
|
/// </summary>
|
public class LinkUtil
|
{
|
/// <summary>
|
/// 基础62位字符
|
/// </summary>
|
private const string _baseKeys = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz";
|
|
/// <summary>
|
/// 幂数
|
/// </summary>
|
private static readonly int _exponent = _baseKeys.Length;
|
|
/// <summary>
|
/// 十进制转62进制
|
/// </summary>
|
/// <param name="value"></param>
|
/// <returns></returns>
|
public static string ConvertTo64(long value)
|
{
|
string result = string.Empty;
|
do
|
{
|
long index = value % _exponent;
|
result = _baseKeys[(int)index] + result;
|
value = (value - index) / _exponent;
|
}
|
while (value > 0);
|
|
return result;
|
}
|
|
/// <summary>
|
/// 混淆十进制转62进制
|
/// </summary>
|
/// <param name="value"></param>
|
/// <returns></returns>
|
public static string MixValueConvertTo64(long value)
|
{
|
long mixValue = InsertRandomBitPer5Bits(value);
|
string result = string.Empty;
|
do
|
{
|
long index = mixValue % _exponent;
|
result = _baseKeys[(int)index] + result;
|
mixValue = (mixValue - index) / _exponent;
|
}
|
while (mixValue > 0);
|
|
return result;
|
}
|
|
/// <summary>
|
/// 62进制转10进制
|
/// </summary>
|
/// <param name="value"></param>
|
/// <returns></returns>
|
public static decimal ConvertTo10(string value)
|
{
|
decimal result = 0;
|
for (int i = 0; i < value.Length; i++)
|
{
|
int x = value.Length - i - 1;
|
result += _baseKeys.IndexOf(value[i]) * Pow(_exponent, x);
|
}
|
return result;
|
}
|
|
/// <summary>
|
/// 一个数据的N次方
|
/// </summary>
|
/// <param name="baseNo"></param>
|
/// <param name="x"></param>
|
/// <returns></returns>
|
private static decimal Pow(decimal baseNo, decimal x)
|
{
|
//1 will be the result for any number's power 0.
|
decimal value = 1;
|
while (x > 0)
|
{
|
value = value * baseNo;
|
x--;
|
}
|
return value;
|
}
|
|
/// <summary>
|
/// 每5位插一个随机位
|
/// </summary>
|
/// <param name="val"></param>
|
/// <returns></returns>
|
private static long InsertRandomBitPer5Bits(long val)
|
{
|
long result = val;
|
long high = val;
|
for (int i = 0; i < 10; i++)
|
{
|
if (high == 0)
|
{
|
break;
|
}
|
Random random = new Random();
|
long num = random.Next(0, 2);
|
int pos = 5 + 5 * i + i;
|
high = result >> pos;
|
result = ((high << 1 | num) << pos) | (result & RightMove(-1L, 64 - pos));
|
}
|
|
return result;
|
}
|
|
/// <summary>
|
/// 无符号右移, 相当于java里的 value>>>pos
|
/// </summary>
|
/// <param name="value"></param>
|
/// <param name="pos"></param>
|
/// <returns></returns>
|
public static long RightMove(long value, int pos)
|
{
|
//移动 0 位时直接返回原值
|
if (pos != 0)
|
{
|
// int.MaxValue = 0x7FFFFFFF 整数最大值
|
long mask = long.MaxValue;
|
//无符号整数最高位不表示正负但操作数还是有符号的,有符号数右移1位,正数时高位补0,负数时高位补1
|
value = value >> 1;
|
//和整数最大值进行逻辑与运算,运算后的结果为忽略表示正负值的最高位
|
value = value & mask;
|
//逻辑运算后的值无符号,对无符号的值直接做右移运算,计算剩下的位
|
value = value >> pos - 1;
|
}
|
|
return value;
|
}
|
}
|
}
|