C - you need to compare the least significant bits nn for equality

C - need to compare n lower bits int for equality.

those. n is 4;

xxxx1001 == xxxx1001 (x does not care)

those. n = 2; xxxxxx01 == xxxxxx01

It is impossible to think of a good way to do this without using a mask, =).

+4
source share
7 answers

Create a mask from among the bits:

 int mask = (1 << bits) - 1; 

Then you use this to compare values:

 if ((a & mask) == (b & mask)) 
+25
source

If you really do not want to use masks (not that something is wrong with that), then you can use the shift-left operator:

 if( a << m == b << m ) { } 

where m is the total number of bits less than the number you are interested in. That is, in the example in question m is 4 (i.e. 8 - 4).

Edit: to be clear - I assumed that the question is an 8-bit integer specified in the format used (for example, xxxx1001), but the solution is general in the sense that it caters for any integer. To determine the number of bits in integers, use 8 * sizeof (type), where the type can be int, short, long, etc.

+9
source

I think what needs to be done is the xor values, and then use the mask. For instance,

 (a ^ b) & (( 1<<n ) - 1) 
+4
source

Try the following:

  int i;
 int theSame = 1;
 for (i = 0; i <n; i ++)
 {
     if! (a >> i & 1) ||  ! (b >> i & 1)
     {
         theSame = 0;
         break;
     }
 }
+1
source

you can use the modulo operator. For example, n = 4, and you should have ints x and y:

 if((x%16) == (y%16)){ .... 

Hope this helps you.

Nick

0
source

What happened with the masks?

 (a & 0x1111) == (b & 0x1111) 
0
source

I presume that the lower 4 bits are first using y = (a ^ b) to obtain a chart of the bit (x is unknown)

 xxxx0000 

Then change the bit pattern with y = ~ y

 xxxx1111 

Then we define the first 0 with y ^ = (y + 1)

 xxx11111 

Then move n times to the right y β†’ = n

 0000xxx1 

If it is not equal to nul, then the lower n bits were equal. So my solution would be

 int are_lowest_n_bits_of_a_and_b_equals(int n,int a, int b) /* return 0 if not equal, or non zero if equal */ { int y=~(a^b); return (y^(y+1))>>n; } 

It seems to work even for n = number_of_bits (int), thanks to the propagation of the sign bit in the shift in the arithmetic shift to the right, but if it was ever UB, we can just check (a == b) in that case the edges.

0
source

All Articles