The Bitwise Operators(Java)

本文详细介绍了Java中的位运算符,包括按位与(&)、按位或(|)、按位异或(^)、按位取反(~)、左移(<<)、右移(>>)及无符号右移(>>>)等操作,并通过实例展示了这些运算符如何在整数变量上工作。

Java defines several bitwise operators, which can be applied to the integer types, long, int, short, char, and byte.

Bitwise operator works on bits and performs bit-by-bit operation. Assume if a = 60; and b = 13; now in binary format they will be as follows:

a = 0011 1100

b = 0000 1101

-----------------

a&b = 0000 1100

a|b = 0011 1101

a^b = 0011 0001

~a  = 1100 0011

The following table lists the bitwise operators:

Assume integer variable A holds 60 and variable B holds 13 then:

Show Examples

SR.NO Operator and Description
1 & (bitwise and)

Binary AND Operator copies a bit to the result if it exists in both operands.

Example: (A & B) will give 12 which is 0000 1100
2 | (bitwise or)

Binary OR Operator copies a bit if it exists in either operand.

Example: (A | B) will give 61 which is 0011 1101
3 ^ (bitwise XOR)

Binary XOR Operator copies the bit if it is set in one operand but not both.

Example: (A ^ B) will give 49 which is 0011 0001
4 ~ (bitwise compliment)

Binary Ones Complement Operator is unary and has the effect of 'flipping' bits.

Example: (~A ) will give -61 which is 1100 0011 in 2's complement form due to a signed binary number.
5 << (left shift)

Binary Left Shift Operator. The left operands value is moved left by the number of bits specified by the right operand

Example: A << 2 will give 240 which is 1111 0000
6 >> (right shift)

Binary Right Shift Operator. The left operands value is moved right by the number of bits specified by the right operand.

Example: A >> 2 will give 15 which is 1111
7 >>> (zero fill right shift)

Shift right zero fill operator. The left operands value is moved right by the number of bits specified by the right operand and shifted values are filled up with zeros.

Example: A >>>2 will give 15 which is 0000 1111
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值