6

以下の動作が理解できません。

バイナリリテラルを使用してバイトマスクを宣言しようとしています:

byte mask = 0b1111_1111;

しかし、次のエラー メッセージが表示されるため、それは不可能です。

型の不一致: int から byte に変換できません

最も興味深いのは、10 進数表現でマスクを直接宣言しようとすると、

byte mask = -1;

エラーは発生しませんが、これら 2 つの表現は完全に等しいはずです。

私は何を間違っていますか?前もって感謝します。

4

5 に答える 5

9

-2^7 to 2^7-1 (-128 to 127)からに値を安全に割り当てることができbyteます。これは 8 ビットであるためです。

ここで0b1111_1111=255

だからそこにキャストが必要です

 byte mask = (byte) 0b1111_1111;
于 2013-09-18T10:39:03.007 に答える
4

The value 0b1111_1111 is equal to 255, outside the byte's range of [-128, 127](because it is signed). Use:

byte mask=(byte)0b1111_1111&0xff;

The narrowing will remove the (all-zero) high bits and fit 8 into 8 without regard for sign.

于 2013-09-18T10:36:17.770 に答える
1

このように型キャストを行うことができます

    byte mask = (byte) 0b1111_1111;
于 2013-09-18T10:38:06.317 に答える
1

すべての数値リテラルは、他の方法でキャストされない限り、または小数点または「e」が含まれていない限り、「int」と見なされます。

于 2013-09-18T10:37:23.953 に答える
1

Your "byte mask" is equivalent to 0xff or 255, which are too large to fit in an 8-bit signed byte, not -1, because the literal in the code is an int. If the value is within the range of a smaller type, the compiler can safely stuff it in there, but it can't safely assign a value outside the range -128..127 to a byte variable, and you'll need a cast.

于 2013-09-18T10:36:11.277 に答える