2

我试图弄清楚如何读取文件(不是由我的程序创建的),使用BinaryReader, 并相应地选中或取消选中一组复选框。

我设法弄清楚复选框是这样存储的:

Checkbox 1 = 00 01
Checkbox 2 = 00 02
Checkbox 3 = 00 04
Checkbox 4 = 00 08
Checkbox 5 = 00 10
Checkbox 6 = 00 20
Checkbox 7 = 00 40
Checkbox 8 = 00 60
Checkbox 9 = 00 80
Checkbox 10 = 01 00
Checkbox 11 = 02 00
etc

因此,如果在文件中选中的复选框 1、2、6 和 10 的十六进制值将是:01 23。我将如何分解它以便检查程序中的正确复选框?

4

3 回答 3

2

以正确的顺序保留 a CheckBox[]orList<CheckBox>CheckBox引用,以便您可以按索引引用它们。您将遍历各个位值并使用计数器来跟踪与该位关联的索引:

short setBits = 0x0123; # short because it is 2 bytes.
short currentBit = 0x0001;
// loop through the indexes (assuming 16 CheckBoxes or fewer)
for (int index = 0; index < checkBoxes.Length; index++) {
    checkBoxes[index].Checked = (setBits & currentBit) == currentBit;
    currentBit <<= 1; // shift one bit left;
}
于 2011-06-05T03:43:48.697 回答
2

我认为您的示例中有一个错字。复选框 8 不应该是 0060,而是 0080。所以 123 表示位:1、2、6、9(不是 10)。

像这样:

Checkbox 01 = 00 01
Checkbox 02 = 00 02
Checkbox 03 = 00 04
Checkbox 04 = 00 08
Checkbox 05 = 00 10
Checkbox 06 = 00 20
Checkbox 07 = 00 40
Checkbox 08 = 00 80
Checkbox 09 = 01 00
Checkbox 10 = 02 00

要检查设置的复选框,您可以使用如下代码:

// var intMask = Convert.ToInt32("0123", 16); // use this line if your input is string
var intMask = 0x0123";
var bitArray = new BitArray(new[] { intMask });
for (var i = 0; i < 16; i++)
{
    var isCheckBoxSet = bitArray.Get(i);
    if (isCheckBoxSet)
        Console.WriteLine("Checkbox {0} is set", i + 1);
}

输出:

Checkbox 1 is set
Checkbox 2 is set
Checkbox 6 is set
Checkbox 9 is set

所以你的带有复选框的代码就像这样简单:

var checkboxes = new List<CheckBox>();
var intMask = 0x0123;
var bitArray = new BitArray(new[] { intMask });
for (var i = 0; i < 16; i++)
    checkboxes.Add(new CheckBox { Checked = bitArray.Get(i) });
于 2011-06-05T03:48:00.707 回答
0

这已经足够了 - 适当调整上限。

for(int i = 0; i < 15; ++i) {
    Checkbox[i + 1].Checked = (yourbits && (1 << i)) != 0
}
于 2011-06-05T03:44:58.273 回答