Access a bit in a Byte, Help!

Im trying to access a bit in a byte. does anyone know how to do this i cant seem to find any documentation on it!

more specifically i want to access bit 2 in the byte that containes boolean values, and i want to return whatever is in bit 2 (whether it be true or false).

can anyone help! please!


Answer this question

Access a bit in a Byte, Help!

  • MyNameisMud

    The result of a bitwise & is an int or a long, even when operating on a byte. Either cast the result, or more simply, use &=:


    receive_buf_array[2] &= 3;
     


    Jon



  • ndhuy

    I am trying to mask a byte value (receive_buff[2]) with a mask value of 3 (bit value 0000 0011) however, I am getting an error of "Cannot implicitly convert type 'int' to 'byte'".

    receive_buf_array[] and receive_buff[] are arrays of bytes.

    Here's my statement:


    receive_buf_array [2]=(receive_buf[2]&3);

     

    What am I doing wrong

  • ROBSR

    John,

    Thanks for your reply. I used your other suggestion in the other thread.

  • jdegaetani

    To see if a bit is set in a byte you do a bitwise "and" operation. That is the "&" operator in C#

    You use a mask to check what is set

    Bit#       Decimal value
    87654321

    00000001 = 1
    00000010 = 2
    00000100 = 4
    00001000 = 8
    00010000 = 16
    00100000 = 32
    01000000 = 64
    10000000 = 128


    So to check if bit 2 is set in a byte we and it with the mask of decimal value of 2 and then see if it is equal to the mask



        Byte byData = ...;
        Byte byMask = 2;

        if ((byData & byMask) == byMask)
        {
           MessageBox.Show("Bit 2 is set!");
        }

     



  • Access a bit in a Byte, Help!