My ASCII85 encoding implementation

by 18. December 2009 23:56

As I tweeted before i have found a c# ASCII 85 encoding implementation. But the link was broken, so i decided to write it by myself. And here it is:

public static string ASCII85(this byte[] data)
{
    // padding 
    int tail = 4 - data.Length % 4;
    byte[] padded_data;

    if (tail != 4)
    {
        padded_data = new byte[data.Length + tail];
        Array.Copy(data, padded_data, data.Length);
    }
    else
    {
        padded_data = data;
    }

   List result = new List(padded_data.Length);

    for (int i = 0; i < padded_data.Length; i += 4)
    {
        uint block_int = 0;

       /* for (int j = 0; j < 4; j++)
        {
            block_int |= (uint)padded_data[i + j] << ((3 - j) * 8);
        }*/

        /*for (int j = 3; j >= 0; j--)
        {
            block_int |= (uint)padded_data[i + (3 - j)] << (j * 8);
        }*/

        block_int = (uint)(padded_data[i] << 24) | (uint)padded_data[i + 1] << 16 | (uint)padded_data[i + 2] << 8 | (uint)padded_data[i + 3];

        if (block_int == 0)
        {
            result.Add((byte)'z');
        }
        else
        {
            uint n = block_int / 52200625;
            result.Add((byte)(33 + n));
            block_int = block_int - n * 52200625;

            n = block_int / 614125;
            result.Add((byte)(33 + n));
            block_int = block_int - n * 614125;

            // if data was padded how to get rid of tail? 

            n = block_int / 7225;
            result.Add((byte)(33 + n));
            block_int = block_int - n * 7225;

            n = block_int / 85;
            result.Add((byte)(33 + n));
            block_int = block_int - n * 85;

            result.Add((byte)(33 + block_int));
        }
    }

    return Encoding.ASCII.GetString(result.ToArray());
}

Tags: ,

My code

Add comment


(Will show your Gravatar icon)

  Country flag

biuquote
  • Comment
  • Preview
Loading



Powered by BlogEngine.NET 1.5.0.7
Theme by Mads Kristensen

About the author

Name: Ilya Khaprov (rus Илья Хапров)

Age: 25

Sex: Male

I'm a postgraduate (an "aspirant" in Russian terminology see Wikipedia for details) at Bryansk State Technical University.

I'm working with .Net since 2004. Also i like lisp.

My research interests lie in the area of Intelligence. In particular i am studing personal information filters, ontology learning, and some other stuff.

Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my employer's view in  anyway.

© Copyright 2011

Recent Visitors