简而言之按位运算 [英] Bitwise Operations on short
问题描述
我正在使用一种称为DDS的技术,在IDL中,它不支持int
.因此,我认为我只会使用short
.我不需要那么多位.但是,当我这样做时:
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);
显示类型不匹配:无法从int转换为short".当我将short
更改为long
时,它可以正常工作.
It says "Type mismatch: Cannot convert from int to short". When I change short
to long
, it works fine.
是否可以在Java中的short
上执行像这样的按位运算?
Is it possible to perform bitwise operations like this on a short
in Java?
推荐答案
对byte
,short
或char
进行任何算术运算时,数字将提升为更宽泛的类型int
.要解决您的问题,请将结果显式转换回short
:
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);
链接:
- 堆栈溢出: Java推广?
- Java语言规范5.6节: http ://java.sun.com/docs/books/jls/second_edition/html/conversions.doc.html#26917
- 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
这篇关于简而言之按位运算的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!