我想读取一二进制文件,并将其转化为相应格式的十进制输出到文本文件中,现在遇到这样一个问题,我的二进制文件按照规定的格式分成了三部分,第一位总是00(标志位),第二三位(也就是第二部分)转化为10进制后的数,是第三部分的长度是变化的,例如:第一位:00 长度是1
   第二位:aa aa 长度是 2
   第三位:xx xx xx xx.....长度是(aa aa)转化十进制后的整数.遇到00则代表新的一条数据.00代表本条数据开始请问一下,这个问题我是不是就得循环读取,请问怎么样实现循环?

解决方案 »

  1.   

    System.IO.BinaryReader binReader = new System.IO.BinaryReader(stream);
    binReader.BaseStream.Seek(1, System.IO.SeekOrigin.Begin);
    int count = binReader.ReadUInt16();
    byte[] data = binReader.ReadBytes(count);
      

  2.   

    public byte[] NewByte = null;       
            public static UInt16 JoinToUInt16(byte byte1, byte byte2)
            {
                return (UInt16)(((UInt16)byte1 << 8) + byte2);
            }
            public static void CombineByte(ref byte[] head, byte[] tail)
            {
                if (head == null)
                    head = tail;
                else
                {
                    if (tail == null)
                        return;
                    int size = head.Length;
                    Array.Resize(ref head, head.Length + tail.Length);                Array.Copy(tail, 0, head, size, tail.Length);
                }
            }
            private void PazeOldData(byte[] buffer)
            {            int Index = 0;
                while (Index < buffer.Length)
                {             
                       byte ID = buffer[Index];                    if (ID == 0)
                        {
                            ushort len = ((JoinToUInt16(buffer[Index++], buffer[Index++])));
                            byte[] newbyte = new byte[Convert.ToInt32(len)];
                            Array.Copy(buffer, Index, newbyte, 0, newbyte.Length);
                            CombineByte(ref NewByte, newbyte);                        Index += newbyte.Length;
                            break;
                        }            
                        Index++;
                }        }
    把二进制读入到buffer中,再调用PazeOldData方法.该方法得到新的NewByte 数组,将该数组转变成十进制,写如文件.