按位运算

我使用的是一种名为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); 

它说“类型不匹配:无法从int转换为short”。 当我改变shortlong ,它工作正常。

是否有可能在Java中执行这样的按位操作?

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

 bit = (short)(bit | 0x00000001); 

链接:

  • Stack Overflow: Java推广?
  • Java语言规范第5.6节: http : //java.sun.com/docs/books/jls/second_edition/html/conversions.doc.html#26917

我的理解是java不支持短文字值。 但这对我有用:

 short bit = 0; short one = 1; short two = 2; short other = (short)~one; System.out.println(bit); bit |= one; System.out.println(bit); bit &= other; bit |= two; System.out.println(bit);