简体   繁体   English

Java On与短裤短路,将其升级为int并返回怪异的值

[英]Java On AND'ing a short with an short, it is upgraded to int and returns weird values

I'm creating a mask and setting higher bits in a short like this: 我正在创建一个掩码,并在短时间内设置较高的位,如下所示:

  enum FLAGS {FLAG1, FLAG2, FLAG3, FLAG4, FLAG5, FLAG6};

  public static void setFlag(short len, FLAGS flag) {
       short mask = 1 << (Short.SIZE - flag.ordinal() - 1);
       len |= mask;
  }

I printed the values: 我打印了值:

  len: 0000001111111100
  mask : 1000000000000000
  after OR'ing with mask: 11111111111111111000001111111100

I understand that when we do bit manipulation on shorts they're upgrded to int to avoid overflow, but why are all the higher bits set then? 我了解到,当我们对短裤进行位操作时,它们会提升为int以避免溢出,但是为什么所有的较高位都被置位呢? How can I simply set any of the first 6 bits without any funny casting? 如何简单地设置前6位中的任何一个而没有任何有趣的转换?

short is signed, and your mask is negative. short已签名,并且您的掩码为负。 That is preserved when it is widened to int . 将其扩展为int时将保留该值。 You can make the higher bits zero by masking the mask: 您可以通过屏蔽掩码将高位设置为零:

len |= (mask & 0xffff);

Now, that would be if len was an int or long , but since it is short it won't have those higher bits anyway. 现在,如果lenintlong ,那将是一个问题,但是由于它很短,因此无论如何都不会有那些更高的位。 So really the widening is happening in some other part of your code. 因此,实际上扩展发生在代码的其他部分。

It looks like you're OR'ing not AND'ing. 看来您是OR或非AND。 '|' '|' is or, '&' is and. 是或,“&”是和。 Also you're OR'ing a short and an int, not a short and a short. 另外,您正在做一个short和一个int,而不是short和short。 Your print statement even says OR'ing, whereas your title says AND'ing. 您的打印语句甚至显示“或”,而标题显示“与”。 If you use '&=' I believe it will solve your problem. 如果您使用'&=',我相信它将解决您的问题。

When the short is converted to an int , its numeric value is preserved. short转换为int ,其数值将保留。 If the highest bit is 1, the short is a negative number, and to preserve its value, the int would have to be negative - that is, the highest bit of the int would have to be 1 also, and so would all the bits in between. 如果最高位是1,则short是一个负数,并且为了保留其值, int必须为负-也就是说, int的最高位也必须为1,因此所有位在两者之间。

In general, when converting a short to an int , negative numbers are left-padded with 1s and positive numbers are left-padded with 0s. 通常,将short转换为int ,负数将用1填充左,正数将用0填充左。

Just cast the result back to short. 只是将结果回短。 You're getting sign-extension in the int result, because bit 0x8000 is set in the mask, which is the sign bit. 由于在掩码中将位0x8000设置为符号位,因此在int结果中将得到符号扩展。

when we do bit manipulation on shorts they're upgrded to int to avoid overflow, 当我们对短裤进行位操作时,它们会升级为int以避免溢出,

No. No overflow is possible, so that can't be the reason. 否。不可能溢出,所以这不是原因。 The reason is for consistency with other operations which can overflow, ie +,-,*,/. 原因是与其他可能溢出的操作(即+,-,*,/)保持一致。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM