2011-06-05 44 views
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.我将如何解决这个问题,以便检查程序中正确的复选框?

回答

2

保留CheckBox[]List<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; 
} 
0

This'd足够 - 适当调整上限。

for(int i = 0; i < 15; ++i) { 
    Checkbox[i + 1].Checked = (yourbits && (1 << i)) != 0 
} 
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) }); 
+0

对于'BitArray' +1。我一定是太舒服了。我宁愿自己使用'BitArray',这取决于还有谁可能维护代码。 – 2011-06-05 03:59:08