CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 3 of 3

Thread: Bit Fiddiling

  1. #1
    Join Date
    Dec 2005
    Posts
    382

    Bit Fiddiling

    I've got a code here that'll determine if a bit is set. So now:

    Code:
    typedef unsigned short ushort_type ; 
     int IsSet(ushort_type x, int i) 
     { 
       /* No out-of-bounds cases */ 
       if (i < 0 || i > MSB) 
         return 0; 
       /* Check if bit is set and return accordingly */ 
       if ( x & ( 1 << i ) ) 
         return 1; 
       else 
         return 0; 
     }
    What I'd like to do is examine two bit pairs from the 16 bit type. In other words consider a 16 bit type:

    Code:
    [15[14[13[12[11[10[9[8[7[6[5[4[3[2[1[0
    I'd like to examine bits [0,1]; [2,3]; [4,5] etc - in other words, the examination is done in pairs. Assume bits, 0 and 1 is set. The returned value would be a 3. Similarily if bit 3 from the set [2,3] is set then the returned value is 2. If 4 is set from the set [4,5] the returned value is a 1.

    While not a programmer by definition, bit fiddiling is certainly not my strong suite. Having slight difficulty achieving this via source. Any help appreciated.

  2. #2
    Join Date
    Aug 2002
    Location
    Madrid
    Posts
    4,588

    Re: Bit Fiddiling

    You can use >> to shift it so that it's always 0,1,2 or 3. You and it with 3 (instead of 1) shifted to the left by i and then right shift it again by i. That's what I understand from your post what you want.
    Get this small utility to do basic syntax highlighting in vBulletin forums (like Codeguru) easily.
    Supports C++ and VB out of the box, but can be configured for other languages.

  3. #3
    Lindley is offline Elite Member Power Poster
    Join Date
    Oct 2007
    Location
    Seattle, WA
    Posts
    10,895

    Re: Bit Fiddiling

    if (i < 0 || i > MSB)

    I suspect you probably meant

    if (i < 0 || i >= MSB)

    Assuming standard C conventions when it comes to indexing.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured