Java – short for bitwise operations

I use a technology called DDS. In IDL, it does not support int. therefore, I think I will use a short one I don't need so many bits But when I do this:

short bit = 0;
System.out.println(bit);
bit = bit | 0x00000001;
System.out.println(bit);
bit = bit & ~0x00000001;
bit = bit | 0x00000002;
System.out.println(bit);

It says "type mismatch: cannot convert from int to short" When I change from short to long, it works normally

Is it possible to perform such bitwise operations in Java?

Solution

When performing any arithmetic on byte, short, or char, the number is promoted to a wider int type To fix your problem, explicitly convert the results to short:

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

Link:

>Stack overflow: promotion in Java? > Java language specification section 5.6: http://java.sun.com/docs/books/jls/second_edition/html/conversions.doc.html#26917

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>