C# 简单字符串压缩算法

2023年2月13日 1780点热度 3人点赞 0条评论
内容纲要
void Main()
{
    string str = "A-A01A05-A01-01-02";
    byte[] data = new byte[16];
    var span = data.AsSpan();

    ulong l = 0;
    int index = 1;
    int count = 0;
    for (int i = 0; i < str.Length; i++)
    {
        var value = HashFind.GetValue(str[i]);
        if (index <= 10)
        {
            l <<= 6;
            l = l | value;
            index++;
        }
        if (index == 11 || i + 1 >= str.Length)
        {
            BinaryPrimitives.TryWriteUInt64LittleEndian(span[count..(count + 8)], l);
            l = 0;
            index = 1;
            count += 8;
        }
    }
    Console.WriteLine(BinaryPrimitives.ReadInt64LittleEndian(data[0..8]));
    Console.WriteLine(BinaryPrimitives.ReadInt64LittleEndian(data[8..16]));
}

public static class HashFind
{
    private const byte A = (byte)'A';      // 65
    private const byte Z = (byte)'Z';      // 90
    private const byte Zero = (byte)'0';   // 48
    private const byte Nine = (byte)'9';   // 57

    //private static readonly char[] Dic = new char[] {'0','1','2','3','4','5','6','7','8','9',
    //                           'A', 'B', 'C', 'D', 'D', 'E', 'E', 'E',
    //                           'E', 'F', 'G', 'H', 'H', 'I', 'J', 'K',
    //                           'L', 'M', 'N', 'O', 'O', 'O', 'O', 'P',
    //                           'Q', 'R', 'R', 'T', 'U', 'U', 'V', 'W',
    //                           'X', 'Y', 'Z','-'};

    public static byte GetValue(char ch)
    {
        if (ch.Equals('-')) return (byte)36;
        var upper = char.ToUpper(ch);
        var value = (byte)upper;
        // 0-9
        if (Zero <= value && value <= Nine)
        {
            return (byte)(value - Zero);
        }
        // 10-35
        else if (A <= value && value <= Z)
        {
            return (byte)(value - A + (byte)10);
        }
        throw new InvalidDataException("字符值不在范围内");
    }
}

痴者工良

高级程序员劝退师

文章评论