Given the number n and two integers p1, p2, determine whether the bits at positions p1 and p2 are the same or not. Positions p1, p2 and 1 are based

I did some small codes to grab onto my coding after graduation, but I got my stump. Here's the question:

Given the number n and two integers p1, p2, determine whether the bits at positions p1 and p2 are the same or not. Positions p1, p2 and 1 are based.

Example

22,3,2 would be true because it is 0001 0110, because position 2 and 3 are the same.

I decided this one way to convert the decimal fractional to binary and then to string and check if the bits in the positions are the same, but I feel that there is an easier way to do with bit manipulations, but I'm not very good with that. I was thinking if I could just shift the bits to the first position and compare them, I could get an answer, but then I ran into a problem when I shift them to the left, as they simply overflow.

+3
source share
8 answers

You can move interesting bits to the least significant position, and then mask all other bits with &.

Assuming that p1and p2are zero-based indices read from the least significant bit:

bool same_bits = (((n >> p1) & 1) == ((n >> p2) & 1))
+5
source
int bitPositionsSame(uint32_t n, uint32_t p1, uint32_t p2) {
        uint32_t i1 =  (n & (1 << p1)) >> p1;
        uint32_t i2 = (n & (1 << p2)) >> p2;
        return (i1 == i2);
}
+1

,

(((0x1 < p1) n) == 0) == (((0x1 < p2) n) == 0)

1 p1/p2, . , , .

, , , :)

: , ...

0

C:

   #define SAMEBIT(n, p1, p2) \
       ((n >> (p1-1)) & (n >> (p2-1)) & 1)

Smalltalk:

   (n bitAt:p1) = (n bitAt:p2)

Java:

   like C
0

& ( ). : p1, p2 - 1 << ( ). n .

0

0 ( 0)

boolean bitPositionsSame(int n, int p1, int p2) {
    return (n & 0x80000000>>>p1)==(n & 0x80000000>>>p2);
}
0
source

Get a bit p1 n:

(n >> (p1-1)) & 1

Get a bit p2 n:

(n >> (p2-1)) & 1

Compare them for equality:

bool result = ((n >> (p1-1))&1) == ((n >> (p2-1))&1)
0
source

Here is another variation:

bool same_bits = !(n & p1 - 1) == !(n & p2 - 1);

Forcing the type of the bitwise AND result to boolwith !limits the possible values ​​to 0or 1.

0
source

All Articles