Inserting bits into byte

Posted by JB_SO on Stack Overflow See other posts from Stack Overflow or by JB_SO
Published on 2010-05-17T14:06:35Z Indexed on 2010/05/17 14:11 UTC
Read the original article Hit count: 306

Filed under:
|
|

I was looking at an example of reading bits from a byte and the implementation looked simple and easy to understand. I was wondering if anyone has a similar example of how to insert bits into a byte or byte array, that is easier to understand and also implement like the example below.

Here is the example I found of reading bits from a byte (http://bytes.com/topic/c-sharp/answers/505085-reading-bits-byte-file):

    static int GetBits3(byte b, int offset, int count)
    {
           return (b >> offset) & ((1 << count) - 1);
    }

Here is what i'm trying to do....and this is my current implementation.....just a little confused with the bit-masking/shifting, etc, that's why I'm trying to find out if there is an easier way to do what i'm doing

BYTE Msg[2];
Msg_Id = 3;
Msg_Event = 1;
Msg_Ready = 2;

Msg[0] = ( ( Msg_Event << 4 ) & 0xF0 ) | ( Msg_Id & 0x0F ) ;
Msg[1] = Msg_Ready  & 0x0F;     //MsgReady & Unused

Thanks for your help!

© Stack Overflow or respective owner

Related posts about c++

Related posts about bits