//button事件。
void BtnCtrlClick(object sender, EventArgs e)
{
BitArray ba=new BitArray(32);
int ctrl;
try
{
ctrl=int.Parse(txtCtrl.Text);
}
catch(System.FormatException)
{
MessageBox.Show("你所输入的不是数字");
return;
}
catch(System.OverflowException)
{
MessageBox.Show("数字超出范围");
return;
}
for(int i=0;i<32;i++)
{
ba[i]=(ctrl & 1<<i)!=0 ? true : false;
}
for(int i=0;i<32;i++)
{
lbl[31-i].BackColor=ba[i] ? Color.Red :Color.Green;
}
}
//在MainForm.cs文件的MainForm类里添加32个控件的代码。
void MainFormLoad(object sender, EventArgs e)
{
for(int i=0;i<32;i++)
{
lbl[i] = new System.Windows.Forms.Label();
lbl[i].Location = new System.Drawing.Point(12*i+20, 40);
lbl[i].Size = new System.Drawing.Size(10, 10);
lbl[i].BackColor=Color.Green;
this.Controls.Add(lbl[i]);
}
}
//位运算索引
public class BitArray
{
int[] bits;
int length;
public BitArray(int length)
{
if(length<0)
{
throw new ArgumentException();
}
bits=new int[((length-1)>>5)+1]; //(length-1)/32+1
this.length=length;
}
public bool this[int index]
{
get
{
if(length<0 || index>=length)
{
throw new IndexOutOfRangeException();
}
return (bits[index>>5] & 1<<index)!=0; //1<<(index%32)
}
set
{
if(length<0 || index>=length)
{
throw new IndexOutOfRangeException();
}
if(value)
{
bits[index>>5] |=1<<index;
}
else
{
bits[index>>5] &=~(1<<index);
}
}
}
}