424,963 Members | 1,260 Online
Need help? Post your question and get tips & solutions from a community of 424,963 IT Pros & Developers. It's quick & easy.

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

 P: 2 How do you check whether the 5th bit and the 2nd bit of the same number are the same? (In C programming) Sep 15 '10 #1
4 Replies

 Expert 100+ P: 2,396 How would you go about isolating these bits? (By "isolate", I mean ignore all the other bits.) Sep 15 '10 #2

 P: 2 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? Sep 15 '10 #3

 Expert 100+ P: 983 Expand|Select|Wrap|Line Numbers ((value&0x20)>>5)==((value&0x04)>>2) Sep 15 '10 #4

 Expert 100+ P: 2,396 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. Expand|Select|Wrap|Line Numbers #include  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. Sep 16 '10 #5