Bitwise Operations简称

8 java bit-manipulation

我使用的是一种名为DDS的技术,在IDL中,它不支持int.所以,我想我会用short.我不需要那么多位.但是,当我这样做时:

short bit = 0;
System.out.println(bit);
bit = bit | 0x00000001;
System.out.println(bit);
bit = bit & ~0x00000001;
bit = bit | 0x00000002;
System.out.println(bit);
Run Code Online (Sandbox Code Playgroud)

它说"类型不匹配:无法从int转换为short".当我换short到时long,它工作正常.

是否有可能short在Java中执行这样的按位运算?

Nay*_*uki 10

在对byte,, short或进行任何算术时,char数字被提升为更宽的类型int.要解决您的问题,请将结果显式转换回short:

bit = (short)(bit | 0x00000001);
Run Code Online (Sandbox Code Playgroud)

链接: