4

nC - int の最下位ビットが等しいかどうかを比較する必要があります。

つまり、n = 4;

xxxx1001 == xxxx1001 (x はどうでもよい)

つまり、n = 2; xxxxxx01 == xxxxxx01

マスクを使わずにそれを行う良い方法は考えられません、=)。

4

7 に答える 7

25

ビット数からマスクを作成します。

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

次に、それを使用して値を比較します。

if ((a & mask) == (b & mask))
于 2009-09-13T11:40:56.950 に答える
9

If you really don't want to use masks (not that there is anything wrong with that!), then you could use a shift-left operator:

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

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

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

于 2009-09-13T11:46:04.490 に答える
4

必要なのは、値を xor してからマスクを使用することだと思います。例えば、

(a ^ b) & (( 1<<n ) - 1)
于 2009-09-13T11:41:16.047 に答える
2

これを試して:

int i;
int theSame = 1;
for (i = 0; i < n; i++)
{
    if !(a >> i & 1) || !(b >> i & 1)
    {
        theSame = 0;
        壊す;
    }
}
于 2009-09-13T20:32:39.547 に答える
0

4つの下位ビットが等しいと仮定します
最初にy =(a ^ b)を使用してこのビットパターンを取得します(xは不明を意味します)

xxxx0000

次に、y=~y でビット パターンを逆にします。

xxxx1111

次に、y^=(y+1) で最初の 0 を検出します。

xxx11111

次に、右に n 回シフトします y>>=n

0000xxx1

nul 以外の場合、最下位の n ビットは等しかったので、私の解決策は次のようになります。

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;
}

符号付き算術右シフトでの符号ビット伝搬のおかげで、 n=number_of_bits(int) でも機能するようですが、UB の場合は、そのようなエッジケースで (a==b) を簡単にテストできます。

于 2012-06-29T00:03:16.407 に答える
0

モジュロ演算子を使用できます。たとえば、n = 4 の場合、x と y を整数にする必要があります。

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

これがお役に立てば幸いです。

ニック

于 2009-09-13T11:40:55.577 に答える
0

マスクの何が悪いの?

(a & 0x1111) == (b & 0x1111)
于 2009-09-13T11:41:02.833 に答える