Question

I am trying to get the functions for converting string to bitarray, date to bitarray time to bitarray byte to bit array. Can anyone please help me with these functions in c#.

Était-ce utile?

La solution

For completeness, I'll include my method for turning arbitrary objects to byte arrays (it's probably faster than a BinaryFormatter and MemoryStream):

public static byte[] ToByteArray(object obj)
{
    int len = Marshal.SizeOf(obj);
    byte[] arr = new byte[len];
    IntPtr ptr = Marshal.AllocHGlobal(len);
    Marshal.StructureToPtr(obj, ptr, true);
    Marshal.Copy(ptr, arr, 0, len);
    Marshal.FreeHGlobal(ptr);
    return arr;
}

Autres conseils

The closest you can get built into the framework is the System.BitConverter class and the System.Text.Encoding.GetBytes() method. Beyond this, you'll need code to convert those byte arrays into bit arrays (though, really, for any sane operation a byte array is better) and none of these cover date/time information (you might look at converting a DateTime's Ticks property instead).

If you consider any type as an object you can use a general method to obtain a byte[]

private byte[] ObjectToByteArray(Object myObject)

{
    if(myObject == null)
        return null;
    BinaryFormatter bF = new BinaryFormatter();
    MemoryStream mS = new MemoryStream();
    bF.Serialize(mS, myObject);
    return ms.ToArray();
}

Then you can feed it to the constructor of BitArray

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top