Skip to content

How to read from a binary file bit by bit

tom thomas

Asked Jun 15, 2009, 11:10 AM EDT2 answers
Share
LinkedInX
DEAR ALL,

I AM A FRESHER IN C SHARP,AND I WOULD LIKE TO REQUEST SOME HELP FROM YOU PEOPLE,I HAVE A BINARY FILE AND I SHOULD READ IT BIT BY BIT  ...COULD ANY OF YOU CAN HELP ME TO SORT THIS OUT??


THANKS IN ADVANCE!!!

THANKS AND REGARDS,
TOM

2 Answers

Know the answer? Post it. Somebody with the same question will find it here.

  • Niradhip Chakraborty
    0
    If you have one binary files with some header, body, etc. Well you might find the following functions very handy:
    You supply an object, e.g your custom structure/class.
    Returns: byte array, you can simply write using BinaryWriter in a file.
    public static byte[] RawSerialize( object anything )
     {
           int rawsize = Marshal.SizeOf( anything );
           IntPtr buffer = Marshal.AllocHGlobal( rawsize );
           Marshal.StructureToPtr( anything, buffer, false );
           byte[] rawdatas = new byte[ rawsize ];
           Marshal.Copy( buffer, rawdatas, 0, rawsize );
           Marshal.FreeHGlobal( buffer );
           return rawdatas;
     }
    For the next one you supply the bytes read from BinaryReader as well as the type of your suctom structure to cast later to.
    Returns object, representing you structure. Note: you must cast to your structure.
    public static object RawDeserialize( byte[] rawdatas, Type anytype )
     {
           int rawsize = Marshal.SizeOf( anytype );
           if( rawsize > rawdatas.Length )
                  return null;
           IntPtr buffer = Marshal.AllocHGlobal( rawsize );
           Marshal.Copy( rawdatas, 0, buffer, rawsize );
           object retobj = Marshal.PtrToStructure( buffer, anytype );
           Marshal.FreeHGlobal( buffer );
           return retobj;
     }
    Now you might need some example how to use the functions above in real life example.
    Lets first have a custo structure:
    [StructLayout(LayoutKind.Sequential)]
    struct SomeFileHeader
    {
          [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 4)]
          public string Signature;
          public Int32 Offset;
          public Int32 Length;
    }
    At last here is an example(you should have already binaryReader assoc to a file):
    //our custom structure
    SomeFileHeader someFileHeader =new SomeFileHeader();
    //temp byte array buffer 
    private byte[] buf =new byte[Marshal.SizeOf(SomeFileHeader ));
    //Read the header from the file stream and save it to an byte array
    buf = binaryReader.ReadBytes(Marshal.SizeOf(SomeFileHead  er ));
                           
    //Deserialization of the byte array (buf) to out PakHeader structure
    someFileHeader = (SomeFileHeader ) RawDeserialize(buf,someFileHeader .GetType());
    After that you should be able to read all members from your struct.
    0
  • 0
    Dear sir,
    the following is the code(please see the code below:) which i uses to open the binary file ,but now the problem is that 2 bytes are read in simultaneously and is being converted into an integer,but i need to read the data from the file in bits and finally convert 8 bits into binary numbers and then to decimal numbers? could you be able to give me some advice ? is it ok if i read all the bytes into a an array and then try to convert it into a bit array?


    with regards,
    tom.


    using System;
    using System.IO;
    using System.Collections;


    class Program
    {
        static void Main()
        {
            R();
        }

        static void R()
        {
            // 1.
            using (BinaryReader b = new BinaryReader(File.Open("file.bin", FileMode.Open)))
            {
                // 2.
                // Position and length variables.
                int pos = 0;
                // 2A.
                // Use BaseStream.
                int length = (int)b.BaseStream.Length;
                while (pos < length)
                {
                    // 3.
                    // Read integer.
                    int v = b.ReadInt32();
                    Console.WriteLine(v);

                    // 4.
                    // Advance our position variable.
                    pos += sizeof(int);

                    // 5.
                    // Seek to our required position.(int pos1 had to be found out )
                    //int pos1 = 0;
                    //b.BaseStream.Seek(pos1, SeekOrigin.Begin);

                    // 6.
                    // Read the next 2000 bytes or required number of bytes int the byte array(int required had to be found out ).
                    //int required = 20000;
                    //byte[] by = b.ReadBytes(required);

                    
                   




                    //.8 convert to bit array
                    //BitArray myBits = new BitArray(by);
                    byte[] value = { 0x11 };
                    BitArray myBits = new BitArray(value);
                
                
                }

                Console.ReadLine();
            }
        }
    }
    ----------------------------------------------------------------------------------------------------------------------------------
    and the following is the data which i gets when i try to open this file with visual studio:
    ÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿþS€DŠ4 ÝýÝÝ}ÕÝ]ÕݝÞÝÝÔ܍¹ÚMŒ×M[Ôm4Ò]Ð\íÍ|ÍÌÜÄÌÜÎÍLÛÎLæÎŒðÏ|øÏŒöÏ\öÏLòÏ ðÏ,öϼúÏíнÑ=Ñ]ÐÝÏìóÎ|ÚÌܾÊ̘È\qÆ OÃÌ-Â<Á<    ¿ëð¾KÙ¼ûƻ˯º+•¸»€·Kj¶[µ{TµO´ëNµUµ«^¶{o·‹{¸{Œ¹ëª¼ǽŒÁü9ÄŒhÈ<™ÊüÆÍ¬îÏÍÑ]$Ó
    9Ô­]ÖÍ}Ù-œÚm±Û]¼ÛýÀÛݲÚݪڭšÙ]‰Ø]€Ö½]Õ
    >Ò­ÐÍÏ\çÍŒËˬ§ÉÌ"Èì‡Ç¬kŬKÃ|#À«ó¾̻˯º+•¸«~·i¶ÜݝØÝ×Ým×ݽÛÝmÍܲÙíˆÖíVÔ=5ÒmÐLïÎÙÍLÙÍ|ÚÍüåμðÏŒþÏìþÏüþÏìÿÏÜûϬ
    0