bit java实验2_java语言中的bit 移位操作

java 位操作符:

取反:~x

- flips each bit to the opposite value.

与操作:AND

x & y

- AND operation between the corresponding bits in x and y.

或操作:OR

x | y

- OR operation between the corresponding bits in x and y.

异或操作:XOR

x ^ y

- XOR operation between the corresponding bits in x and y.

左移操作:Shift left

x << y

- shifts x to the left by y bits. The high order bits are lost while zeros fill the right bits.

将x左移y位,移动过程中,高位会丢失

有符号数右移操作:Shift Right - Signed

x >> y

- shifts x to the right by y bits. The low order bits are lost while the sign bit value (0 for positive numbers, 1 for negative) fills in the left bits.

无符号数右移:Shift Right - Unsigned

x >>> y

- shifts x to the right by y bits. The low order bits are lost while zeros fill in the left bits regardless of the sign.

例子:

下面的例子显示如何将一个int数组通过移位操作压缩到一个int内保存,其原理是在java语言中,int类型使用4 bytes来保存,因此对于需要压缩的int数组,其中的每一个int值的大小不能超过255(2的8次方-1),因此这只是一个实例:

int [] aRGB = {0x56, 0x78, 0x9A, 0xBC};   // 是用16进制保存的4种颜色值

int color_val = aRGB[3];

color_val = color_val | (aRGB[2] << 8);  // 为了压缩,需要放置到color_val值的第二个字节位置上:将aRGB[2] 左移到第二个byte,同时与color_val进行或操作,下面同理

color_val = color_val | (aRGB[1] << 16);

color_val = color_val | (aRBG[0] << 24);

操作完的结果是56 78 9A BC

如果要从colorVal 还原为int数组,或者得到数组中的某个值,只需要对colorVal 进行相应的右移操作即可:

int alpha_val = (colorVal >>> 24) & 0xFF;

int red_val   = (colorVal >>> 16) & 0xFF;

int green_val = (colorVal >>>  8) & 0xFF;

int blue_val  =  colorVal & 0xFF;

参考资料:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值