Best way to store / retrieve bits C# [duplicate]

旧时模样 提交于 2019-12-02 03:00:32

Why not use a specially designed class BitArray?

http://msdn.microsoft.com/query/dev11.query?appId=Dev11IDEF1&l=EN-US&k=k(System.Collections.BitArray);k(TargetFrameworkMoniker-.NETFramework,Version%3Dv4.5);k(DevLang-csharp)&rd=true

e.g.

  BitArray array = new BitArray(150); // <- up to 150 bits

  ...
  array[140] = true;  // <- set 140th bit 
  array[130] = false; // <- reset 130th bit 
  ...
  if (array[120]) {   // <- if 120th bit is set
    ...

There are several ways to go about this, based on the limitations of the database you are using.

If you are able to store byte arrays within the database, you can use the BitArray class. You can pass the constructor a byte array, use it to easily check and set each bit by index, and then use it's built in CopyTo method to copy it back out into a byte array.

Example:

byte[] statusBytes = yourDatabase.Get("passed_failed_bits");
BitArray statusBits = new BitArray(statusBytes);
...
statusBits[65] = false;
statusBits[66] = true;
...
statusBits.CopyTo(statusBytes, 0);
yourDatabase.Set("passed_failed_bits", statusBytes);

If the database is unable to deal with raw byte arrays, you can always encode the byte array as a hex string:

string hex = BitConverter.ToString(statusBytes);
hex.Replace("-","");

and then get it back into a byte array again:

int numberChars = hex.Length;
byte[] statusBytes= new byte[numberChars / 2];
for (int i = 0; i < numberChars; i += 2) {
    statusBytes[i / 2] = Convert.ToByte(hex.Substring(i, 2), 16);
}

And if you can't even store strings, there are more creative ways to turn the byte array into multiple longs or doubles.

Also, if space efficiency is an issue, there are other, more efficient (but more complicated) ways to encode bytes as ascii text by using more of the character range without using control characters. You may also want to look into Run Length Encoding the byte array, if you're finding the data remains the same value for long stretches.

Hope this helps!

Why not use a string instead? You could put a very large number of characters in the database (use VARCHAR and not NVARCHAR since you control the input).

Using your example, if you had "11111", you could skip bitwise operations and just do things like this:

string myBits = "11111";
bool failedPosition0 = myBits[0] == '1';
bool failedPosition1 = myBits[1] == '1';
bool failedPosition2 = myBits[2] == '1';
bool failedPosition3 = myBits[3] == '1';
bool failedPosition4 = myBits[4] == '1';
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!