JAVA移位运算符-左移、右移、无符号右移

1.左移
    左移运算符“<<” - 使指定值的所有位都左移规定的次数。
    左移m<<n 代表把数字m在无溢出的前提下乘以2的n次方。

    例如,5<<3 就是5乘以2的3次方,结果是40。

 

2.右移
 右移运算符“>>” - 使指定值的所有位都右移规定的次数。
    右移m>>n 代表把数字m除以2的n次方,原来是正数的还是正数,负数还是负数。注意,如果是单数,也就是二进制末位为1,则结果是将m除以2的n次方的整数商。

    例如,16>>3 就是16除以2的3次方,结果是2。

              15>>3 就是14(15-1)除以2的3次方,结果是1。

 

3.无符号右移
    无符号右移运算符“>>>” - 同右移,但是结果全变正数。

 

### Java 中位运算符左移右移)的用法 #### 左移运算符 `<<` 左移运算符`<<`会将指定的操作数按二进制形式向左移动指定位数,在低位补零。每左移一位相当于乘以2。 对于正数而言,左移的结果总是正值;而对于负数,则保持其符号不变并相应扩大数值绝对值。需要注意的是,如果超出存储范围则会发生溢出[^1]。 ```java public class LeftShiftExample { public static void main(String[] args) { int number = 4; // Binary: 0000 0100 System.out.println(number << 1); // Output will be 8 (Binary: 0000 1000) byte b = 1; System.out.println(b << 3); // Output is 8 because binary of 1 is shifted three times to the left resulting into binary value which equals decimal 8. } } ``` #### 右移运算符 `>>` 右移运算符`>>`用于执行带符号右移操作,即高位填充原最高有效位的值(对于正数填0,对于负数填1),从而实现除以2的效果,并向下取整至最接近的整数值[^4]。 ```java public class RightShiftExample { public static void main(String[] args) { int positiveNumber = 8; // Binary: 0000 1000 int negativeNumber = -8; // In two's complement form System.out.println(positiveNumber >> 1); // Outputs 4 since it divides by 2 and rounds down System.out.println(negativeNumber >> 1); // Also outputs a large negative integer due to sign extension (-4 in this case). } } ``` #### 无符号右移运算符 `>>>` 不同于普通的有符号右移(`>>`),无符号右移`>>>`无论被移位的数据是什么样的符号都会在左边补充0来完成整个过程。这意味着即使是负数也会变成正数[^2]。 ```java public class UnsignedRightShiftExample { public static void main(String[] args) { int num = -8; // Two’s Complement Representation as Negative Number System.out.println(num >>> 1); // This shifts bits one position towards least significant bit while inserting '0' at MSB making final result non-negative. } } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值