Bit operations on short

I use a technology called DDS and in IDL, it does not support int . So, I decided that I was just using short . I don't need so 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 of mismatch: cannot be converted from int to short." When I change short to long , it works fine.

Is it possible to perform bitwise operations like this on short in Java?

+6
source share
2 answers

When doing any arithmetic on byte , short or char numbers advance to the wider int type. To solve your problem, explicitly return the result to short :

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

References:

+9
source

I understand that java does not support short literals. But it helped 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); 
+1
source

Source: https://habr.com/ru/post/894749/


All Articles