我怎样才能快速编码和压缩,然后含在C#中数字的短字符串 [英] How can I quickly encode and then compress a short string containing numbers in c#

查看:126
本文介绍了我怎样才能快速编码和压缩,然后含在C#中数字的短字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个看起来像这样的字符串:

I have strings that look like this:

000101456890
348324000433
888000033380

它们是字符串都具有相同的长度和它们只包含数字。

They are strings that are all the same length and they contain only numbers.

我想找到一种方法来进行编码,然后ompress(缩短长度)的字符串。压缩algoithm需要只压缩至ASCII字符,因为这些将被用作网页链接。

I would like to find a way to encode and then ompress (reduce the length) of the strings. The compression algoithm would need to just compress down to ASCII characters as these will be used as web page links.

因此​​,例如:

www.stackoverflow.com/000101456890  goes to www.stackoverflow.com/aJks

有没有一些方法,我可以做到这一点,有些方法会做快速压缩的工作。

Is there some way I could do this, some method that would do the job of compressing quickly.

谢谢,

推荐答案

要做到这一点的只是的,你可以考虑每一个(充足的房间里有),和十六进制编码; ,让你:

To do it simply, you could consider each as a long (plenty of room there), and hex-encode; that gives you:

60c1bfa
5119ba72b1
cec0ed3264

基础-64将是短,但你需要把它看成大端(注意大多数.NET是小端),而忽略领先的0字节。这就给了你:

base-64 would be shorter, but you'd need to look at it as big-endian (note most .NET is little-endian) and ignore leading 0 bytes. That gives you:

Bgwb+g==
URm6crE=
zsDtMmQ=

例如:

    static void Main()
    {
        long x = 000101456890L, y = 348324000433L, z = 888000033380L;

        Console.WriteLine(Convert.ToString(x, 16));
        Console.WriteLine(Convert.ToString(y, 16));
        Console.WriteLine(Convert.ToString(y, 16));

        Console.WriteLine(Pack(x));
        Console.WriteLine(Pack(y));
        Console.WriteLine(Pack(z));

        Console.WriteLine(Convert.ToInt64("60c1bfa", 16).ToString().PadLeft(12, '0'));
        Console.WriteLine(Convert.ToInt64("5119ba72b1", 16).ToString().PadLeft(12, '0'));
        Console.WriteLine(Convert.ToInt64("cec0ed3264", 16).ToString().PadLeft(12, '0'));

        Console.WriteLine(Unpack("Bgwb+g==").ToString().PadLeft(12, '0'));
        Console.WriteLine(Unpack("URm6crE=").ToString().PadLeft(12, '0'));
        Console.WriteLine(Unpack("zsDtMmQ=").ToString().PadLeft(12, '0'));

    }
    static string Pack(long value)
    {
        ulong a = (ulong)value; // make shift easy
        List<byte> bytes = new List<byte>(8);
        while (a != 0)
        {
            bytes.Add((byte)a);
            a >>= 8;
        }
        bytes.Reverse();
        var chunk = bytes.ToArray();
        return Convert.ToBase64String(chunk);
    }
    static long Unpack(string value)
    {
        var chunk = Convert.FromBase64String(value);
        ulong a = 0;
        for (int i = 0; i < chunk.Length; i++)
        {
            a <<= 8;
            a |= chunk[i];
        }
        return (long)a;
    }

这篇关于我怎样才能快速编码和压缩,然后含在C#中数字的短字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆