一 引言
最近在查看JDK1.8的源码,分析integer.java文件,发现用到一些位运算,遂网上了解一番。
二 正文
下面的a和b都是整数类型,则:
含义 | C语言 | C#语言 | Java | |
---|---|---|---|---|
按位与 | a and b | a & b | a & b | a & b |
a or b | a | b | a | b | a | b | |
按位 | a xor b | a ^ b | a ^ b | a ^ b |
按位 | not a | ~a | ~a | ~a |
左移 | a shl b | a << b | a << b | a << b |
带符号 | a shr b | a >> b | a >> b | a >> b |
无符号右移 | a>>> b |
例子:
按位与 同符号
0b00000000000000000000000000001011
0B011111111111111111111111111111110B00000000000000000000000000001011 OK按位与 不同符号0b000000000000000000000000000010110B100000000000000000000000000000010B00000000000000000000000000000001 OK 按位异或 同符号0b000000000000000000000000000010110B011111111111111111111111111111110B01111111111111111111111111110100 OK按位异或 不同符号0b000000000000000000000000000010110B100000000000000000000000000000010B10000000000000000000000000001010 OK按位取反 正整数0b000000000000000000000000000010110b11111111111111111111111111110100 OK按位取反 负整数0B100000000000000000000000000000010B01111111111111111111111111111110 OK左移2位 正数0b000000000000000000000000000010110b00000000000000000000000000101100 OK左移2位 负整数0B100000000000000000000000000000010B00000000000000000000000000000100 OK