0

ビットマスキングを使用して、数値のすべてのビットがすべて 0 の場合は 1 に、そうでない場合はすべて 0 にするにはどうすればよいですか?

符号なし変数の使用:

だから、私が持っているなら0000-0000、私はそれがなりたい1111-1111です。0101-0110(または0000-0001、または、など) がある場合1111-1111、それを にしたいと思い0000-0000ます。

これは、条件を使用せずに行うことは可能ですか?

4

3 に答える 3

2

おそらく効率的な方法ではありません。

本当にしたい場合は、次のことができます。

int mask = 0;
int result = 0;


for(int i = 0; i < sizeof(number) * 8; i++)
{
    mask |= number & 1 << i;
}


for(int i = 0; i < sizeof(number) * 8; i++)
{
    result |= mask & 1 << i;
}

~結果があなたの答えです。

于 2013-08-23T16:47:26.557 に答える
0

これはどう:

def check_for_zero(value):
    # Same as "if value == 0: return 0; else: return 1"
    # value must be an 8-bit number.

    # Need to check all 8 bits of value.  But we can compress it...
    x = value | (value >> 4)
    # Now just need to check the low 4 bits of x.  Compress again...
    x = x | (x >> 2)
    # Now just need to check the low 2 bits of x.  Compress again...
    x = x | (x >> 1)
    # Now just need to check the low 1 bit of x.  Success!
    return x & 1

def expand_to_8bit(bit):
    # Same as "if bit == 0: return 0; else: return 255"
    # Must pass bit == 0 or bit == 1

    # bit is a 1-bit value.  Expand it...
    x = bit | (bit << 1)
    # x is a 2-bit value.  Expand it...
    x = x | (x << 2)
    # x is a 4-bit value.  Expand it...
    x = x | (x << 4)
    # x is a 8-bit value.  Done!
    return x

def foo(value):
    x = check_for_zero(value)
    x = x ^ 1  # Flips the bit
    return expand_to_8bit(x)
于 2013-08-23T17:03:28.180 に答える