By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
424,963 Members | 1,260 Online
Bytes IT Community
+ Ask a Question
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
Share this Question
Share on Google+
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

Oralloy
Expert 100+
P: 983
Expand|Select|Wrap|Line Numbers
  1. ((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
  1. #include <stdbool.h>
  2. bool isMatchingBits(unsigned long value, unsigned long mask) {
  3.     const unsigned long isolatedBits = value & mask;
  4.     return ((isolatedBits == 0uL) || (isolatedBits == mask));
  5. }
By the way, it is usually safer to use an unsigned type when working with individual bits.
Sep 16 '10 #5

Post your reply

Sign in to post your reply or Sign up for a free account.