字节数组的表示比BASE64更紧凑?

Roy*_* T. 2 c# character-encoding

对于调试,我经常发现将字节数组(例如散列密码)可视化为BASE64字符串很有用.

        public override string ToString()
        {
            return Convert.ToBase64String(this.Hash);      
        }
Run Code Online (Sandbox Code Playgroud)

但是对于大的哈希值(例如超过32个字节),BASE64编码会生成一个很长的字符串.这使得很难通过查看它们来快速比较它们.

BASE64仅使用64个可打印字符.我想知道是否有其他编码技术使用超过64个字符(但仍然只能打印字符)来减少表示32个字节所需的长度.在我看来,我们可以大大改善,因为在我的键盘上我已经看到94个易于区分的可打印键.

当然,使字节数组很容易被人类比较并不是BASE64最初的目的.但无论有效,对吧?;)

ren*_*ene 6

你可以使用Ascii85.维基百科说:

Ascii85,也称为Base85,是由Paul E. Rutter为btoa实用程序开发的二进制文本编码形式.通过使用五个ASCII字符来表示四个字节的二进制数据(使编码大小¹/ 4大于原始值,假设每个ASCII字符为8位),它比uuencode或Base64更有效,它使用四个字符来表示三个字节数据的增加(¹/ 3增加,假设每个ASCII字符有8位).

你可以在github上找到由Jeff Atwood编写的ac#implementation ,他在他的博客上附上了一个帖子

由于您只需要编码器部分,我使用Jeff的代码作为开始,并创建了仅包含编码部分的实现:

class Ascii85
{

    private const int _asciiOffset = 33;
    private const int decodedBlockLength = 4;

    private byte[] _encodedBlock = new byte[5];
    private uint _tuple;

    /// <summary>
    /// Encodes binary data into a plaintext ASCII85 format string
    /// </summary>
    /// <param name="ba">binary data to encode</param>
    /// <returns>ASCII85 encoded string</returns>
    public string Encode(byte[] ba)
    {
        StringBuilder sb = new StringBuilder((int)(ba.Length * (_encodedBlock.Length / decodedBlockLength)));

        int count = 0;
        _tuple = 0;
        foreach (byte b in ba)
        {
            if (count >= decodedBlockLength - 1)
            {
                _tuple |= b;
                if (_tuple == 0)
                {
                    sb.Append('z');
                }
                else
                {
                    EncodeBlock(_encodedBlock.Length, sb);
                }
                _tuple = 0;
                count = 0;
            }
            else
            {
                _tuple |= (uint)(b << (24 - (count * 8)));
                count++;
            }
        }

        // if we have some bytes left over at the end..
        if (count > 0)
        {
            EncodeBlock(count + 1, sb);
        }

        return sb.ToString();
    }

    private void EncodeBlock(int count, StringBuilder sb)
    {
        for (int i = _encodedBlock.Length - 1; i >= 0; i--)
        {
            _encodedBlock[i] = (byte)((_tuple % 85) + _asciiOffset);
            _tuple /= 85;
        }

        for (int i = 0; i < count; i++)
        {
            sb.Append((char)_encodedBlock[i]);
        }

    }
}
Run Code Online (Sandbox Code Playgroud)

这是必需的归因:

/// <summary>
/// adapted from the Jeff Atwood code to only have the encoder
/// 
/// C# implementation of ASCII85 encoding. 
/// Based on C code from http://www.stillhq.com/cgi-bin/cvsweb/ascii85/
/// </summary>
/// <remarks>
/// Jeff Atwood
/// http://www.codinghorror.com/blog/archives/000410.html
/// </remarks>
Run Code Online (Sandbox Code Playgroud)