How to save a C# BitArray using SQL Server
Posted on 2008-06-26
I have a BitArray in C# and need to be able to retrieve it from, and save it in, SQL Server 2005.
How can I do this? I have tried writing the BitArray to a byte arrays using the CopyTo method and then encoding the byte array using the GetString of System.Text.Encoding. This works fine in C# - I can code a bit array as a string and decode the string as a bit array. However, when the string is saved in the database table as a varchar (or nvarchar) and later retrieved, bits are lost. In particular, the problem seems to lie with bit7 of each byte. I have checked the string just before storing it and all is OK. I have also checked it on retrieving it and it is there the missing bits arise.
I can work around this by ensuring expanding the bitarray so every 7th bit of the bit array has a 0 and then contracting the retrieved bit array by removing these 0s, but this seems clumsy.
My questions are
(a) What is actually happening and
(b) What is the best way to implement this?