简而言之按位运算 [英] Bitwise Operations on short

查看:93
本文介绍了简而言之按位运算的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用一种称为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?

推荐答案

byteshortchar进行任何算术运算时,数字将提升为更宽泛的类型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);

链接:

  • 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆