Home > Software design >  C# How do I set specific binary bit to 0 or 1?
C# How do I set specific binary bit to 0 or 1?

Time:12-06

I've got four checkboxes linked to a hex value between 0x00 and 0x0F, so if you type in 0x0B which would be 1011 the check boxes would be checked, not checked, checked, checked. For this I used:

if ((controlByte.Item2 & 0x01) == 0x01)
{
    control1 = true;
}
if ((controlByte.Item2 & 0x02) == 0x02)
{
    control2 = true;
}
if ((controlByte.Item2 & 0x04) == 0x04)
{
    control3 = true;
}
if ((controlByte.Item2 & 0x08) == 0x08)
{
    control4 = true;
}

Next I want it to go the other direction, so as you click checkboxes the hex value will change.

If I have the current value 0x0B (1011) And click the first box I want it to return 0x0A (1010). My function will go over each checkbox and update the hex value as it goes. My current attempt looks like this:

if (checkbox1)
{
    controlbyte = (byte)(controlbyte | 0x01);
}
else
{
    controlbyte = (byte)(controlbyte ^ 0x01);
}

It looks like this toggles it, but when I run through all checkboxes it toggles ones I didn't click. Is there a better way to take 0x0B (1011) and just set one of the bits to 0 or 1?

CodePudding user response:

( 1 << flag ) <--- change like this; 
if ((controlByte.Item2 & (1 << flag)) == (1 << flag))
{
    control[flag] = true;
}
//0x01 == 1 << 1;
//0x02 == 1 << 2;
//0x04 == 1 << 3;
//0x08 == 1 << 4;
//because it same like this:

if ((controlByte.Item2 & (1 << 1)) == (1 << 1))
{
    control1 = true;
}

if ((controlByte.Item2 & (1 << 2)) == (1 << 2))
{
    control2 = true;
}

if ((controlByte.Item2 & (1 << 3)) == (1 << 3))
{
    control3 = true;
}

...

controlbyte = (byte)(controlbyte | (1 << 1));

controlbyte = (byte)(controlbyte ^ (1 << 1));
  • Related