ASCIIHexDecode,RunLengthDecode

 public static byte[] ASCIIHexDecode(byte[] data)
        {
            MemoryStream outResult = new MemoryStream();
            bool first = true;
            int n1 = 0;
            for (int k = 0; k < data.Length; ++k)
            {
                int ch = data[k] & 0xff;
                if (ch == '>')
                    break;
                if (isWhitespace(ch))
                    continue;
                int n = getHex(ch);
                if (n == -1)
                    throw new Exception("Illegal character in ASCIIHexDecode.");
                if (first)
                    n1 = n;
                else

                    outResult.WriteByte((byte)( ((n1 << 4) + n)));
                first = !first;
            }
            if (!first)
                outResult.WriteByte((byte)((n1 << 4)));
            return outResult.ToArray();
        }


        public static bool isWhitespace(int ch)
        {
            return (ch == 0 || ch == 9 || ch == 10 || ch == 12 || ch == 13 || ch == 32);
        }

        public static int getHex(int v)
        {
            if (v >= '0' && v <= '9')
                return v - '0';
            if (v >= 'A' && v <= 'F')
                return v - 'A' + 10;
            if (v >= 'a' && v <= 'f')
                return v - 'a' + 10;
            return -1;
        }
View Code
public static byte[] RunLengthDecode(byte[] data)
        {


            // allocate the output buffer
            MemoryStream outResult = new MemoryStream();
            int dupAmount = -1;
            for (int i = 0; i < data.Length; i++)
            {
                if ((dupAmount = (int)data[i]) != -1 && dupAmount != 128)
                {
                    if (dupAmount <= 127)
                    {
                        int amountToCopy = dupAmount + 1;
                        for (int j = 0; j < amountToCopy; j++)
                        {
                            if (++i < data.Length)
                            {
                                outResult.WriteByte((byte)( data[i]));
                            }
                            else
                            {
                                break;
                            }
                        }
                    }
                    else
                    {
                        if (++i < data.Length)
                        {
                            byte dupByte = data[i];
                            for (int j = 0; j < 257 - (int)(dupAmount & 0xFF); j++)
                            {
                                outResult.WriteByte((byte)(dupByte));
                            }
                        }
                    }
                }
                else
                {
                    break;
                }
            }
            return outResult.ToArray();
        }
View Code

 

posted @ 2013-11-07 14:49  法的空间  阅读(914)  评论(0编辑  收藏  举报