views:

110

answers:

3
+2  Q: 

C++ bit shifting

Hi, I am new to working with bits & bytes in C++ and I'm looking at some previously developed code and I need some help in understanding what is going on with the code. There is a byte array and populating it with some data and I noticed that the data was being '&' with a 0x0F (Please see code snipped below). I don't really understand what is going on there....if somebody could please explain that, it would be greatly 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
+1  A: 
x & 0xF

returns the low four bits of the data.

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 become zero, and the bottom four bits will become what they were before the operation.

WhirlWind
+2  A: 

0x0f is 00001111 in binary. When you perform a bitwise-and (&) with this, it has the effect of masking off the top four bits of the char (because 0 & anything is always 0).

James McNellis
Ok, now if my bits 3:0 were not unsed and need to have some data in there (ex. int y = 5), how would this implementation below change to include 'y'. ThanksMsg_Arry[0] = Msg_Id
JB_SO
@JB_SO: You need to shift a number to place it into bits other than the least significant bits, using the left shift operator (and to get it back out, you'd use the right shift operator): http://en.wikipedia.org/wiki/Logical_shift (you'll need to make sure your `BYTE` type is unsigned).
James McNellis
A: 

In the given example, it actually does nothing. Msg_Id and AckMsg_Id are both less than 0x0F, and so masking them has no effect here.

However the use of the bitwise-and operator (&) on integer types performs a bit for bit AND between the given operands.

Matt Joiner
The bitwise-and only works for integer types, not all POD types.
James McNellis
Thanks James, slipped my mind.
Matt Joiner