2011-06-05 31 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