Bit masking

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • randysimes
    New Member
    • Oct 2009
    • 54

    Bit masking

    I have a 32bit number (unsigned int), I want to set another 32bit number to only a certain series of bits. For instance:
    1000 0000 1011 1010 0111 1001 1101 0011 is what is given.

    I want to set another number to bits 3 - 16 from the left, so bits 17 - 30.

    I tried newNum = (given & 0x3FFF0000) but it is incorrect.
    1000 0000 1011 1010 0111 1001 1101 0011given
    0011 1111 1111 1111 0000 0000 0000 0000mask
    ---------------------------------------------------------------
    The correct answer is 0000 0000 1011 1010 0000 0000 0000 0000

    What am I doing wrong?
  • donbock
    Recognized Expert Top Contributor
    • Mar 2008
    • 2427

    #2
    You told us the "correct" answer ... what is the "wrong" answer that prompted you to post this question?

    Comment

    • hype261
      New Member
      • Apr 2010
      • 207

      #3
      Not the best at Bit masking

      I am not the best at bit masking, but I believe you need to do
      int newNum = given & 0x00FF0000

      Comment

      • weaknessforcats
        Recognized Expert Expert
        • Mar 2007
        • 9214

        #4
        If you have:

        1100

        (which is 12 decinal) and you want to change it to:

        1110

        (which is 14 decimal)

        you need to set bit 1 (counting from right).

        To get a 1 in position 1 you use 1 < 1 which is 0010. Then you OR:

        1100
        0010
        and the OR result is:

        1110.

        Code:
        unsigned int data = 12;    //the 1100
        data = data | 1 <1;
        To turn the bit off you create a mask where the desired bit is off and all the other bits are ON. The mask for 0010 is 1101:

        1110
        1101
        and the AND result is

        1100.

        Code:
        data = data & ~(1<1);    // the bitwise not reverses 1's and 0's.
        I'm sure this is in a book somewhere (like the C Programming Language).

        Do not use this in C++. Use the bitset template instead.

        Comment

        Working...