How do you check whether the 5th bit and the 2nd bit of the same number are the same?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • mikeymyman
    New Member
    • Sep 2010
    • 2

    #1

    How do you check whether the 5th bit and the 2nd bit of the same number are the same?

    How do you check whether the 5th bit and the 2nd bit of the same number are the same? (In C programming)
  • donbock
    Recognized Expert Top Contributor
    • Mar 2008
    • 2427

    #2
    How would you go about isolating these bits?
    (By "isolate", I mean ignore all the other bits.)

    Comment

    • mikeymyman
      New Member
      • Sep 2010
      • 2

      #3
      Bit mask only the 5th bit and the 2nd bit? But how do you compare these two bits if they are part of the same number?

      Comment

      • Oralloy
        Recognized Expert Contributor
        • Jun 2010
        • 988

        #4
        Code:
        ((value&0x20)>>5)==((value&0x04)>>2)

        Comment

        • donbock
          Recognized Expert Top Contributor
          • Mar 2008
          • 2427

          #5
          If the bits are equal to each other then they must either all be equal to 0 or all be equal to 1. The following C code works for comparing any number of bits.
          Code:
          #include <stdbool.h>
          bool isMatchingBits(unsigned long value, unsigned long mask) {
              const unsigned long isolatedBits = value & mask;
              return ((isolatedBits == 0uL) || (isolatedBits == mask));
          }
          By the way, it is usually safer to use an unsigned type when working with individual bits.

          Comment

          Working...