C ++ bit shift

I am new to working with bits and bytes in C ++ and I am looking at some previously developed code and I need help understanding what is going on with the code. There is a byte array and is filled with some data, and I noticed that the data was "&" with 0x0F (see the code below). I don't quite understand what's going on there. If anyone can explain this it would be very apperciated. Thanks!

//Message Definition
/*
Byte 1: Bit(s) 3:0 = Unused; set to zero
Bit(s) 7:4 = Message ID; set to 10
*/

/*
Byte 2: Bit(s) 3:0 = Unused; set to zero
Bit(s) 7:4 = Acknowledge Message ID; set to 11
*/    

    //Implementation

    BYTE Msg_Arry[2];
    int Msg_Id = 10;
    int AckMsg_Id = 11;


    Msg_Arry[0] = Msg_Id  & 0x0F;       //MsgID & Unused
    Msg_Arry[1] = AckMsg_Id & 0x0F;     //AckMsgID & Unused

      

+2


a source to share


3 answers


0x0f

00001111

in binary format. When you do bitwise and ( &

) with that, it has the effect of masking the top four bits of the char (because it 0 & anything

always does 0

).



+2


a source


x & 0xF

      

returns the lowest four data bits.



If you think of the binary representation of x and use the and operator with 0x0f (00001111 in binary), the top four bits of x will always be zero, and the bottom four bits will be what they were before the operation.

+1


a source


In this example, it actually does nothing. Msg_Id

and AckMsg_Id

less than 0x0F

, and therefore their masking has no effect here.

However, using the bitwise and operator ( &

) for integer types does a bit for the AND bits between the given operands.

0


a source







All Articles