问题
I am using a technology called DDS and in the IDL, it does not support int
. So, I figured I would just use short
. I don't need that many bits. However, 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 short
to long
, it works fine.
Is it possible to perform bitwise operations like this on a short
in Java?
回答1:
When doing any arithmetic on byte
, short
, or char
, the numbers are promoted to the wider type int
. To solve your problem, explicitly cast the result back to short
:
bit = (short)(bit | 0x00000001);
Links:
- 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
回答2:
My understanding is that java does not support short literal values. But this did work for me:
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);
来源:https://stackoverflow.com/questions/7015997/bitwise-operations-on-short